我正在尝试收集一些 json 数据,将它们放在一个字符串中,并通过 toast 在我的应用程序中显示它们以进行测试。我很确定服务器允许我并响应我的请求,因为之前在 Fiddler 上使用相同的 URL(URI)测试了 GET 方法。
这是活动/课程代码:
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI("http://scards.cloudapp.net/api/AddressBooks/3"));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
try {
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String page = sb.toString();
Toast.makeText(this, page, Toast.LENGTH_LONG).show();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在 LogCat 中,它显示我有 android.os.NetworkOnMainThreadException。接受建议和更正。
项目属性:SDK:API16 - Android 4.1.2,minBuilSDK:API:7 Android 2.1(Eclair) - Eclipse SDK 4.2