素材巴巴 > 程序开发 >

HTTP Post请求响应报文乱码(Accept-Encoding:gzip)

程序开发 2023-09-09 13:57:46
  今天在发送HTTP Post请求时,响应报文有时正常,有时乱码,也不是中文乱码,响应报文整个乱码,最开始以为是InputStreamReader读取的时候字符编码导致,然后使用utf-8:InputStreamReader isr = new InputStreamReader(is, "utf-8");但是还是乱码,然后又想到可能是请求头的字符编码不正确导致,可是请求头也是utf-8,也不是这个问题导致的,经过抓包发现,响应报文体乱码的请求头比不乱码的报文请求头多个属性:Accept-Encoding=gzip,这个问题之前是遇到过的,但是突然忘记了,请求头带Accept-Encoding=gzip的时候,响应报文会被压缩,所以解决办法有两种:第一种(简单粗暴):请求头中去掉Accept-Encoding的gzip即可
 

在这里插入图片描述

第二种(解码):
 判断响应报文头中是否存在"Content-Encoding"属性,如果有,则判断是否存在"gzip",如果存在,则进行解压,
 否则正常读取即可
 

 /**
 * 发送请求
 * @param requestUrl 请求URL
 * @param requestMethod 请求方法
 * @param outputJsonStr 请求参数
 * @param proxy 是否代理
 * @return
 * @throws Exception
 */
 public static Map httpRequestJson(String requestUrl, String requestMethod, String outputJsonStr, Proxy proxy) throws Exception {Map resMap = new HashMap();StringBuffer buffer = new StringBuffer();HttpsURLConnection conn = null;InputStream is = null;OutputStream os = null;try {URL url = new URL(requestUrl);if (null != proxy) {// 忽略ssl证书不信任SslUtil.ignoreSsl();// 打开连接conn = (HttpsURLConnection) url.openConnection(proxy);} else {conn = (HttpsURLConnection) url.openConnection();}conn.setRequestMethod(requestMethod);// 设置请求头信息HttpHeadUtil.setSpdReqHead(conn);//往服务器端写内容 也就是发起http请求需要带的参数if (null != outputJsonStr) {os = conn.getOutputStream();os.write(outputJsonStr.getBytes());}os.flush();//读取服务器端返回的内容Map> head = conn.getHeaderFields();is = conn.getInputStream();List contentEncoding = (List)head.get("Content-Encoding");// 判断是否存在Content-Encoding属性及属性值是否存在gizpif (null != contentEncoding && (contentEncoding.contains("gzip") || contentEncoding.contains("GZIP"))) {
 //                System.out.println("响应:"+ SpdConstant.zipInputStream(is));// gzip解压buffer = SpdConstant.zipInputStream(is);} else {InputStreamReader isr = new InputStreamReader(is, "utf-8");BufferedReader br = new BufferedReader(isr);String line = null;while ((line = br.readLine()) != null) {System.out.println("line:"+line);buffer.append(line);}}System.out.println("body:" + buffer.toString());resMap.put("head", head);resMap.put("body", buffer.toString());} catch (Exception e) {throw e;} finally {if (null != is) {is.close();}if (null != os) {os.close();}}return resMap;}/*** GZIP解压* 解决Content-Encoding: gzip 的问题* @param is 输入字节流* @return* @throws IOException*/public static StringBuffer zipInputStream(InputStream is) throws IOException {GZIPInputStream gzip = new GZIPInputStream(is);BufferedReader in = new BufferedReader(new InputStreamReader(gzip, "UTF-8"));StringBuffer buffer = new StringBuffer();String line;while ((line = in.readLine()) != null)buffer.append(line + "n");return buffer;}

标签:

上一篇: 谈谈.NET CORE OAuth 2.0 下一篇:
素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。