我通过方法从 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
,响应将自动解压缩。
关于java - 编码 HttpResponse UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31142051/