在Android中将gzip json响应解压缩为字符串 [英] Decompress gzip json response to string in Android

查看:706
本文介绍了在Android中将gzip json响应解压缩为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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��;������

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

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

推荐答案

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

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

这篇关于在Android中将gzip json响应解压缩为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆