commons-httpclient post请求乱码问题记录(非编码问题,gzip格式问题)
来源:互联网 发布:淘宝预售发货时间 编辑:程序博客网 时间:2024/06/05 03:47
最近工作中需要使用commons-httpclient模拟请求拿到返回值,在浏览器上面直接请求很正常,如图 :
但是代码返回的结果却是乱码,如下:
byte[] bs = new byte[] { 31, -117, 8, 0, 0, 0, 0, 0, 0, 0, -85, 86, 42, -54, 47, 47, 86, -78, -118, -82, 86, 42, -82, 44, 14, -87, 44, 72, 85, -78, 82, 50, 84, -46, 81, 42, 45, 78, 45, -14, 76, 1, 114, -116, 77, -52, -108, 106, 99, 117, -108, -118, 74, -14, -100, -13, 83, 32, -46, -75, 0, -27, 121, -125, -98, 55, 0, 0, 0 }; String r2 = new String(bs, "utf-8"); String r3 = new String(bs, "gbk"); String r4 = new String(bs, "ISO8859-1"); String r5 = new String(bs); String r6 = new String(r3.getBytes(), "utf-8"); System.out.println(r2); System.out.println(r3); System.out.println(r4); System.out.println(r5); System.out.println(r6);
确定不是编码问题后,反编译jar,debug看代码,试了很多次都没发现问题,
偶然发现浏览器返回的值是用gzip编码的,如下 :
而是试着看下模拟请求是否也是一样,结果如下 :
确定原因后,只要解压一下就可以了 :
if(rtnStatus==200){ Header[] header=post.getResponseHeaders("Content-Encoding"); if(header!=null&&header.length>0){ if("gzip".equals(header[0].getValue())){ rtnJson = new String(uncompress(post.getResponseBody())); }else{ rtnJson = new String(post.getResponseBody(), "UTF-8"); } }else{ rtnJson = new String(post.getResponseBody(), "UTF-8"); } }
public static String uncompress(byte[] bytes) throws IOException { if (bytes == null || bytes.length == 0) { return ""; } ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); GZIPInputStream gunzip = new GZIPInputStream(in); byte[] buffer = new byte[256]; int n; while ((n = gunzip.read(buffer)) >= 0) { out.write(buffer, 0, n); } return out.toString("utf-8"); }
结果如下 :
全文完
。 0 0
- commons-httpclient post请求乱码问题记录(非编码问题,gzip格式问题)
- org.apache.commons.httpclient.HttpClient请求乱码问题
- HttpClient POST 中文乱码问题
- HttpClient GZip压缩问题
- get post请求乱码问题
- 处理post请求乱码问题
- post&get请求编码问题
- OkHttp post请求编码问题
- HttpClient POST 的 UTF-8 编码问题
- HttpClient POST 的 UTF-8 编码问题
- HttpClient POST的中文编码问题
- HttpClient POST的中文编码问题
- HttpClient POST的中文编码问题
- HttpClient POST的中文编码问题
- HttpClient POST的中文编码问题
- httpclient 的 doPost请求中文乱码问题
- HttpClient 请求参数中文编码问题
- Spring学习笔记(三十五):关于httpClient的post请求,到后台中文乱码的问题
- 浅谈MVP in Android
- java Socket实现简单在线聊天(二)
- 注册码生成器 略屌略屌
- apache支持php解析(php安装后无法解析脚本)
- PHP的命名空间
- commons-httpclient post请求乱码问题记录(非编码问题,gzip格式问题)
- How to send Email through external SMTP server on Ubuntu 14.04
- Java基础---泛型
- 64位linux下inet_ntop()返回值竟然为int,printf报段错误
- android 任务Task及回收栈back stack介绍
- Lesson 3 Time Complexity PermMissingElem
- 36.[Leetcode]Valid Sudoku
- 1乘1
- ios开发证书CER文件、P12文件,mobileprovition许可文件的用途