gpt4 book ai didi

java - 从 URL 检索 JSON 时,Android Bad Request IOException

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:28 25 4
gpt4 key购买 nike

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

并且不返回结果。

我该如何解决这个问题?

谢谢!

最佳答案

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

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

关于java - 从 URL 检索 JSON 时,Android Bad Request IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30011783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com