天天看点

JAVA Httpclient 调接口 gzip格式返回值乱码

当调接口返回的值是压缩过的,如果不做处理就会得到一长串乱码。

//此处是将请求体封装成为了StringEntity,若乱码则指定utf-8
            StringEntity se = new StringEntity(jsonstr,"utf-8");
            //  StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            Header[] headers = response.getHeaders("Content-Encoding");
            boolean isGzip = false;
            for(Header h:headers){
                if(h.getValue().equals("gzip")){
                    //返回头中含有gzip
                    isGzip = true;
                }
            }

            if(isGzip){
                //需要进行gzip解压处理
                result = EntityUtils.toString(new GzipDecompressingEntity(response.getEntity()));
            }else{
                result = EntityUtils.toString(response.getEntity());
            }