我從我的Android設備連接到Webservice,然後發送參數並獲取json。 它確定當我測試與Android API < 4.0 ex 2.3.3 當我測試與另一個設備,它的API是4.0.3,4.0.4 然後我無法接收JSON。僅接收json時出錯Android 4.0
這是我的代碼
json = getJson("http://search.twitter.com/search.json?result_type=recent&rpp=3&q=iphone");
private String getJson(String uri) {
String json = null;
try {
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
Log.d(TAG,"1");
// conn.setConnectTimeout(10 * 1000); //6s
if (conn.getResponseCode() == 200) {
// get successfull
// read Json
Log.d(TAG,"2");
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
int len = 0;
byte[] buf = new byte[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((len = in.read(buf)) != -1) {
String s = new String(buf, 0, len);
stringBuffer.append(s);
}
Log.d(TAG,"3");
json = stringBuffer.toString();
Log.d(TAG,json);
}
} catch (Exception e) {
Log.e(TAG, "error get json :" + e.toString());
json = null;
}
return json;
}
錯誤。
11-20 19:42:22.555: E/TEST(29097): error get json :android.os.NetworkOnMainThreadException