我通过方法从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的响应进行编码吗?
更新:[SOLVED]我用方法解决了问题
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