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

来源:互联网 发布:汽车资源软件下载 编辑:程序博客网 时间:2024/06/04 01:25

项目生产环境往往会有这样的需求,内网的生产环境的应用需要访问互联网上第三方的服务,但又出于安全考虑,不允许该生产机直接访问互联网,这时我们往往通过代理方式来实现网外服务的访问:我们可以在可访问互联网的机器上,使用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();            }        }
原创粉丝点击