我整个晚上都在努力从google图书API中获得ISBN号码。到目前为止,在尝试了So和Google的几种解决方案之后,我在下面的代码中发现了一行"BufferedReader responseReader =新BufferedReader.“中的错误。
我的头完全被堵住了,所以任何帮助都会非常感谢.
(我有API密钥,在测试期间不在这里使用)
代码:
public void getGoogle(View v) {
String result = "";
String link = "https://www.googleapis.com/books/v1/volumes?q=intitle:'farmer+boy'+inauthor:'laura+ingalls+wilder'&projection=full&langRestrict=en&maxResults=1";
HttpURLConnection connection = null;
try
{
URL url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
}
catch (Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
}
try
{
StringBuilder builder = new StringBuilder();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "iso-8859-1"),8);
String line = responseReader.readLine();
while (line != null){
builder.append(line + "\n");
line = responseReader.readLine();
}
connection.disconnect();
result = builder.toString();
}
catch (Exception e)
{
Log.e("log_tag", "Error converting result: " + e.toString());
}
// parse json data
try
{
JSONArray jArray = new JSONArray(result);
String isbn;
JSONObject json = jArray.getJSONObject(0);
isbn = json.getString("kind");
EditText isbnfld = (EditText) findViewById(R.id.isbn);
isbnfld.setText(isbn);
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(), "Error parsing data.", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Problem importing data.", Toast.LENGTH_LONG).show();
}
}LOGCAT:
12-04 11:32:06.025: E/log_tag(1761): Error converting result: android.os.NetworkOnMainThreadException发布于 2013-12-04 17:20:20
我也有一个类似的错误,拖出一个大的JSON响应。我从BufferedReader改为使用BasicResponseHandler。试试这个:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("https://www.googleapis.com/books/v1/volumes?q=intitle:'farmer+boy'+inauthor:'laura+ingalls+wilder'&projection=full&langRestrict=en&maxResults=1");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = null;
try{
responseBody = client.execute(get, responseHandler);
}catch(Exception ex) {
ex.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(responseBody);
System.out.println("JSONRESPONSE ="+jsonObject);
}catch(Exception ex){
Log.v("TEST","Exception: " + ex.getMessage());
}https://stackoverflow.com/questions/20381536
复制相似问题