Decompress gzip json response to string in Android

百般思念 提交于 2019-12-12 04:44:58

问题


This is my code:

try {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(strJson, "UTF-8"));
    httpPost.setHeader("api_key", "<TSssssssssssssaaa7>");
    httpPost.setHeader("Content-Type", "application/json");
    httpPost.setHeader("Accept-Encoding", "gzip");
    response = httpClient.execute(httpPost);
    resp=EntityUtils.toString(response.getEntity(), "UTF-8");

    Log.w("QueingSystem", strJson);
    Log.w("QueingSystem", EntityUtils.toString(response.getEntity(), "UTF-8"));
    Log.w("QueingSystem", EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
    Log.d("InputStream", e.getLocalizedMessage());
}

And my output in the log is as follows:

��������������V*J-.��+NU��VJ�O�&�:J���ʼn�@��ciIFj^IfrbIf~��[bfNj�Rm-���n��;������

Can any one please help me to get the exact output of json response in String format?


回答1:


You have to manually check whether the response is gzip compressed. If it is you can wrap the response entity into a GzipDecompressingEntity to handle the decompression:

// setup request
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(strJson, "UTF-8"));
httpPost.setHeader("api_key", "<TSssssssssssssaaa7>");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "gzip");
// execute request
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();

// handle gzip compression
Header contentEncodingHeader = entity.getContentEncoding();
if (contentEncodingHeader != null) {
    HeaderElement[] encodings = contentEncodingHeader.getElements();
    for (HeaderElement encoding : encodings) {
        if (encoding.getName().equalsIgnoreCase("gzip")) {
            entity = new GzipDecompressingEntity(entity);
            break;
        }
    }
}

// get response content
resp = EntityUtils.toString(entity, "UTF-8");


来源:https://stackoverflow.com/questions/42586541/decompress-gzip-json-response-to-string-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!