【发布时间】:2015-07-12 18:08:21
【问题描述】:
我正在使用以下代码从 URL 获取 JSON 对象:
public JSONObject makeRequest(String url) throws IOException, JSONException {
JSONObject response;
String jsonString;
HttpClient httpclient = new DefaultHttpClient();
// create the request
HttpUriRequest request = new HttpGet(url);
request.addHeader("Accept-Encoding", "gzip");
// execute the request
HttpResponse resp = httpclient.execute(request);
StatusLine statusLine = resp.getStatusLine();
// check the request response status. Should be 200 OK
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
Header contentEncoding = resp.getFirstHeader("Content-Encoding");
InputStream instream = resp.getEntity().getContent();
// was the returned response gzip'ed?
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder responseString = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
jsonString = responseString.toString();
response = new JSONObject(jsonString);
} else {
resp.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
return response;
}
但我收到一条错误消息,提示此行有错误的请求:
throw new IOException(statusLine.getReasonPhrase());
并且不返回结果。
我该如何解决这个问题?
谢谢!
【问题讨论】:
-
您确定您的清单中有互联网权限吗?
标签: java android json httprequest ioexception