Illegal character ((CTRL-CHAR, code 31))问题排查 gzip接口返回 RestTemplate GET POST请求

Illegal character ((CTRL-CHAR, code 31))问题排查 gzip接口返回

#接口返回gzip方式
private static final String ENCODING_UTF8 = "UTF-8";
private static ObjectMapper mapper = new ObjectMapper();

private void writeResponse(HttpServletResponse response, Object outJB){
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setContentType("text/html; charset=utf-8");
        //response.setContentType("application/json; charset=utf-8");
        //response.setContentType("text/json; charset=utf-8");
        response.setCharacterEncoding(ENCODING_UTF8);
        response.setHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        //byte[] jsonOut = null;
        String jsonOut = null;
        try {
//            mapper.setSerializationInclusion(Include.ALWAYS); 
            jsonOut = mapper.writeValueAsString(outJB);
            out = new GZIPOutputStream(response.getOutputStream());   
            out.write(jsonOut.getBytes(ENCODING_UTF8));
            out.flush();   
        } catch (Exception e) {
            logger.error("",e);
        } finally{
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

1.非gzip接口请求方式

//RestTemplate POST/PUT请求
    //requestVO请求参数
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add("Content-Type", "application/json;charset=UTF-8");
    //            requestHeaders.add("User-Agent", "mysite_web");
    requestHeaders.add("connection", "Keep-Alive");
    //            requestHeaders.add("Accept", "application/json;version=3.0;compress=false");

    RestTemplate template = new RestTemplate();
    HttpEntity<String> requestEntity = new HttpEntity<>(GsonUtils.toJson(requestVO), requestHeaders);
    logger.info("url=" + serverURL + "/console/test/testRemark/add" );
    ResponseEntity<ResponseData> response = template.exchange(serverURL + "/console/test/testRemark/add",
            HttpMethod.POST, requestEntity, ResponseData.class);

    ResponseData httpResult = response.getBody();
    logger.info("httpResult=" + GsonUtils.toJson(httpResult));

    
    //RestTemplate GET请求
    //请求参数跟在url后面
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add("Content-Type", "application/json;charset=UTF-8");
    //            requestHeaders.add("User-Agent", "mysite_web");
    requestHeaders.add("connection", "Keep-Alive");
    //            requestHeaders.add("Accept", "application/json;version=3.0;compress=false");

    RestTemplate template = new RestTemplate();
    HttpEntity<String> requestEntity = new HttpEntity<>(null, requestHeaders);
    logger.info("url=" + serverURL + "/console/test/testRemark/add?参数1=aa&参数2=bb" );
    ResponseEntity<ResponseData> response = template.exchange(serverURL + "/console/test/testRemark/add?参数1=aa&参数2=bb",
            HttpMethod.GET, requestEntity, ResponseData.class);

    ResponseData httpResult = response.getBody();
    logger.info("httpResult=" + GsonUtils.toJson(httpResult));

2.gzip接口请求方式

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * 请求接口返回gzip的http工具类
 */
public class HttpUtil {

    public class HttpResult {

        private String resCode;
        private String resMsg;
        private Object data;

        public String getResCode() {
            return resCode;
        }

        public void setResCode(String resCode) {
            this.resCode = resCode;
        }

        public String getResMsg() {
            return resMsg;
        }

        public void setResMsg(String resMsg) {
            this.resMsg = resMsg;
        }

        public Object getData() {
            return data;
        }

        public void setData(Object data) {
            this.data = data;
        }
    }

    private static final String POST = "POST";
    private static final String GET = "GET";
    private static final String DELETE = "DELETE";
    private static final String PUT = "PUT";

    private static final String ENCODEING = "UTF-8";

    public static HttpResult get(String reqUrl) throws Exception{
        String result = send(reqUrl, "", GET);
        System.out.println("reqUrl="+reqUrl+";result="+result);

        ObjectMapper om = new ObjectMapper();
        return om.readValue(result, HttpResult.class);
    }

    public static HttpResult post(String reqUrl, String reqContent) throws Exception{
        String result = send(reqUrl, reqContent, POST);
        System.out.println("reqUrl="+reqUrl+";result="+result);

        ObjectMapper om = new ObjectMapper();
        return om.readValue(result, HttpResult.class);
    }


    private static String send(String reqUrl, String reqContent, String method) throws Exception {
        String resContent = null;

        HttpURLConnection conn = null;
        GZIPOutputStream out = null;
        GZIPInputStream in = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(reqUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(100000);
            conn.setReadTimeout(100000);


            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(false);//是否自动处理重定向
            conn.setRequestMethod(method);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");//传递参数使用 &链接的表单提交方式
            conn.setRequestProperty("User-Agent", "mysite_web");

            conn.connect();
            //java.util.zip.ZipException: Not in GZIP format
            if (!method.equals(GET)) {
                out = new GZIPOutputStream(conn.getOutputStream());
                //发送请求数据
                out.write(reqContent.getBytes(ENCODEING));
                out.flush();
                out.close();
            }

            //接收返回数据
            int resCode = conn.getResponseCode();
            if(resCode == 200){
                in = new GZIPInputStream(conn.getInputStream());
                reader = new BufferedReader(new InputStreamReader(in, ENCODEING));
                resContent = reader.readLine();
            }else{
                System.out.println("服务器返回码:"+resCode);
            }
        } catch (Exception e) {
            throw e;
        } finally{
            if(reader != null){
                reader.close();
            }
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null){
                conn.disconnect();
            }
        }
        return resContent;
    }
}

 

posted on 2022-10-08 17:16  oktokeep  阅读(699)  评论(0编辑  收藏  举报