gpt4 book ai didi

java - 编码 HttpResponse UTF-8

转载 作者:行者123 更新时间:2023-12-02 04:33:29 25 4
gpt4 key购买 nike

我通过方法从 url 获取 HttpResponse:

public void getResponse(String url) {
String response;
String str;
BufferedReader bf;
GZIPInputStream gzip;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

HttpGet httpGet = new HttpGet(url);

httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity, HTTP.UTF_8);

System.out.println(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

但是我得到的响应是这样的错误:

�P:�ˎ�#�I���!h����Ab���9�xQ�7۰=b��x<M����n�

我检查了“HttpEntity”的内容编码是“gzip”。那么,是否有任何建议将响应编码为 utf8?

更新:[已解决]我用方法解决了问题:

public void getResponse(String url) {
String response;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

HttpGet httpGet = new HttpGet(url);

httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(final HttpResponse response,
final HttpContext context) throws HttpException,
IOException {
HttpEntity entity = response.getEntity();
Header encheader = entity.getContentEncoding();
if (encheader != null) {
HeaderElement[] codecs = encheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GzipDecompressingEntity(entity));
return;
}
}
}
}
});

httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity, HTTP.UTF_8);

System.out.println(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

最佳答案

不要使用DefaultHttpClient,使用DecompressingHttpClient,响应将自动解压缩。

参见http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/DecompressingHttpClient.html

关于java - 编码 HttpResponse UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31142051/

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