我整晚都在尝试从书名中获取谷歌图书API的ISBN号。在尝试了SO和谷歌的几个解决方案之后,到目前为止,我已经到了下面的代码,我在“BufferedReader responseReader = new BufferedReader ........”中遇到错误。
我的头现在完全被封锁了,所以任何帮助都会非常感激...
(我有API Key,我在测试期间没有使用它)
CODE:
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
答案 0 :(得分:1)
我在拉大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());
}