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

时间:2025-03-17 08:37:17
/** * 发送请求 * @param requestUrl 请求URL * @param requestMethod 请求方法 * @param outputJsonStr 请求参数 * @param proxy 是否代理 * @return * @throws Exception */ public static Map<String, Object> httpRequestJson(String requestUrl, String requestMethod, String outputJsonStr, Proxy proxy) throws Exception { Map<String, Object> resMap = new HashMap<String, Object>(); 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<String, List<String>> head = conn.getHeaderFields(); is = conn.getInputStream(); List<String> contentEncoding = (List<String>)head.get("Content-Encoding"); // 判断是否存在Content-Encoding属性及属性值是否存在gizp if (null != contentEncoding && (contentEncoding.contains("gzip") || contentEncoding.contains("GZIP"))) { // ("响应:"+ (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; }