从URL检索JSON时,Android出现Bad Request IOException

4

我正在使用以下代码从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());

结果没有返回。

我该如何处理?

谢谢!


你确定你在清单文件中开启了互联网权限吗? - Shehabic
1个回答

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();
}

关于这个问题没有太多的解释,这是一个单行请求和响应,所以在一行中您可以发出请求并接收响应。然后,您只需获取根 JSONObject并随意操作即可 :) - Yurets
那么这两行代码与上面的整个代码是一样的吗? - Apple
ROOT_ELEMENT是获取根元素的标准值,还是我需要用其他东西替换它?因为我的JSON没有命名的根元素。 - Apple
请记得在后台执行并在“清单文件”中添加网络权限。如果您的JSONResponsekey,则使用“根元素”。否则,您可以直接使用json - Yurets
这个不起作用。我收到一个错误,说“类型字符串无法转换为JSON对象”。是的,我已经添加了权限并在后台执行了。 - Apple
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接