我使用以下代码从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());
并且不返回结果。
我该如何解决这个问题?
谢谢!
答案 0 :(得分:0)
尝试使用此代码。很简单。
try {//Making a request to server getting entities
JSONObject json = new JSONObject(EntityUtils.toString(new DefaultHttpClient().execute(new HttpGet(URL)).getEntity()));
//getting json root object
JSONObject obj = json.getJSONObject("ROOT_ELEMENT");
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}