在Android中解压缩gzip json对字符串的响应

时间:2017-03-03 19:00:53

标签: android json gzip apache-httpclient-4.x

这是我的代码:

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

我在日志中的输出如下:

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

任何人都可以帮我以String格式获取json响应的确切输出吗?

1 个答案:

答案 0 :(得分:0)

您必须手动检查响应是否是gzip压缩的。如果是,您可以将响应实体包装到GzipDecompressingEntity以处理解压缩:

// 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");