当调接口返回的值是压缩过的,如果不做处理就会得到一长串乱码。
解决方案:
在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()); }