java httpClient使用代理实现外网访问

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wzl19870309/article/details/72323541

项目生产环境往往会有这样的需求,内网的生产环境的应用需要访问互联网上第三方的服务,但又出于安全考虑,不允许该生产机直接访问互联网,这时我们往往通过代理方式来实现网外服务的访问:我们可以在可访问互联网的机器上,使用nginx或者apache做代理,然后通过httpClient的代理机制实现。

以下是httpClient使用代理的代码片段:

        String document = objectMapper.writeValueAsString(requestObj);
        HttpClient httpClient = clientBuilder.build();
        // 依次是代理地址,代理端口号,协议类型  
        HttpHost proxy = new HttpHost(代理地址, 代理端口, "http");
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();  
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(document, "UTF-8"));
        httpPost.addHeader("Content-Type", "application/xml;charset=utf-8");
        httpPost.setConfig(config); 

        CloseableHttpResponse response = null;
        try{
            response = (CloseableHttpResponse)httpClient.execute(target,httpPost);
        }finally{
            if(response != null){
                response.close();
            }
            if(httpPost != null){
                httpPost.abort();
            }
        }

猜你喜欢

转载自blog.csdn.net/wzl19870309/article/details/72323541