Sinh Phan
Sinh Phan

Reputation: 1266

Encoding HttpResponse UTF-8

I get HttpResponse from url by method:

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

but the response i got error like:

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

I checked the content encoding of 'HttpEntity' is 'gzip'. So, Is there any suggestion to encode response to utf8?

Update: [SOLVED] I solved problem with method:

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

Upvotes: 0

Views: 6240

Answers (1)

Qwerky
Qwerky

Reputation: 18435

Don't use the DefaultHttpClient, use DecompressingHttpClient and the response will be uncompressed automatically.

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

Upvotes: 2

Related Questions