【问题标题】:Android Bad Request IOException when retrieving JSON from URL从 URL 检索 JSON 时 Android Bad Request IOException
【发布时间】: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


【解决方案1】:

尝试改用此代码。简化了很多。

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

【讨论】:

  • 这个我不太明白。你能详细说明答案吗?我在代码中的什么地方使用它?
  • 这里没有太多解释,这是单行请求和响应,所以在 1 行中你发出请求并接收响应。然后你只需获取root JSONObject 并随心所欲地使用它:)
  • 那么这两行代码和上面的整个代码一样吗?
  • ROOT_ELEMENT 是获取根元素的标准值还是我需要用某些东西替换它?因为我的 JSON 没有命名的根元素。
  • 记得在后台执行它并添加Internet权限到Manifest。如果您的 JSONResponse 具有 key,则为“根元素”。如果没有,您可以立即使用json
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
  • 2018-04-22
  • 2016-02-10
  • 2016-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多