编码 HttpResponse UTF-8

Encoding HttpResponse UTF-8

我通过以下方法从 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