【发布时间】:2015-07-04 03:21:55
【问题描述】:
我在从我的 Android 应用程序中的给定 URL 接收 JSON 列表响应时遇到了一些困难。我不确定我是否错过了触发 GET 调用的步骤,或者问题出在 Web 服务端。就在代码到达“getInputStream”行时,它崩溃了
if (url != null) {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
catch (IOException e) {
e.printStackTrace();
}
}
以下给出的错误与 NetworkOnMainThread 异常以及其他一些异常有关。 注意:这是在“onCreate”方法中调用的方法中,这也可能是问题的根源。
【问题讨论】:
-
尝试注释掉 setRequestMethod。我相当确定连接默认为 GET。
-
没用...我想知道是否应该将它放在 ASyncTask 中并尝试一下?
-
NetworkOnMainThread,把它放在一个AsyncTask中。
标签: java android json get httpurlconnection