【问题标题】:Decompress gzip json response to string in Android在Android中解压gzip json响应到字符串
【发布时间】:2017-03-03 19:00:53
【问题描述】:

这是我的代码:

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

谁能帮我得到字符串格式的json响应的确切输出?

【问题讨论】:

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


    【解决方案1】:

    您必须手动检查响应是否经过 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");
    

    【讨论】:

    • entity = new GzipDecompressingEntity(entity);我得到一个错误无法解决
    猜你喜欢
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2023-03-16
    • 2013-01-15
    相关资源
    最近更新 更多