我从我的 Android 设备连接到 Webservice,然后发送参数并获取 json。当我用 android API < 4.0 ex 2.3.3 测试时没问题当我用另一台设备测试时,它的 api 是 4.0.3, 4.0.4 然后我无法接收 json。
这是我的代码
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