httpclient通过流转发post请求到新的http服务

最近公司采用spring cloud gateway 重构了以前的 openApi 网关,因为接入的中台很多,不可能让他们一个去改成新的网关,新的网关又需要全面的测试以保证上线时没有问题,就写了一个 将 老网关的请求转向新网关的 方法

public boolean forward(HttpServletRequest request, HttpServletResponse response , String serviceName) throws IOException {
        String[] serviceNames = forwardname.split(";");
            
            String requestURI = request.getRequestURI();//获取请求URI
            String queryParam=request.getQueryString();//获取请求url中的参数
            String url=  targetUrl + requestURI;
            if(StringUtils.isNoneBlank(queryParam)) {
                url = url + "?" + queryParam;
            }
            logger.info(serviceName + "=================== forward to " + url  );
            
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost(url);
            
            Map headerMap = getHeadersInfo(request, null);
            for(Map.Entry entry : headerMap.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
            
            InputStream inputstream =  request.getInputStream(); //获取post请求中的流,并直接以流的形式转发到新网关
            InputStreamEntity inputEntity = new InputStreamEntity(inputstream); //直接、
            httpPost.setEntity(inputEntity);
            httpPost.removeHeaders("Content-Length");
            CloseableHttpResponse threadResponse = httpclient.execute(httpPost);
            
            Header[] headers = threadResponse.getAllHeaders();
            
            String result = null;
            StatusLine statusLine = threadResponse.getStatusLine();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = threadResponse.getEntity();
                threadResponse.getAllHeaders();
                if (entity != null) {
                    result = EntityUtils.toString(entity, "UTF-8");
                }
            } else {
                result = JSON.toJSONString(statusLine);
            }
            if(headers != null ) {
        //response的设置响应头
                for(Header header : headers) {
                    response.setHeader(header.getName(), header.getValue());
                }
            }
            try {
                logger.info("forward response headers ==============" + JSON.toJSONString(headers));
                logger.info("forward response body ==============" + result);
//直接返回新网关响应的内容
                PrintWriter writer = response.getWriter();
                writer.print(result);
                writer.flush();
                writer.close();
            } catch (Exception e) {
                logger.error("Write body to response error, " + e.getMessage());
            } 
            return false;
    }

你可能感兴趣的:(httpclient通过流转发post请求到新的http服务)