我是靠谱客的博主 感动世界,这篇文章主要介绍HttpClient使用代理,现在分享给大家,希望可以做个参考。

一、Maven依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

二、工具方法

/**
     * 构建的HTTP客户端
     * @param useProxy
     * @param proxyIp
     * @param proxyPort
     * @return
     * @author: fuyang.qin
     * @date: 2020/12/16
     */
private CloseableHttpClient buildHttpClient(String useProxy, String proxyIp, String proxyPort) {
        CloseableHttpClient httpClient;
        if (useProxyFlag.equals(useProxy.toLowerCase())) {
            // 代理
            HttpHost pr = new HttpHost(proxyIp, Integer.parseInt(proxyPort), "http");
            RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(pr).build();
            httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
        } else {
            // 非代理
            httpClient = HttpClients.createDefault();
        }
        return httpClient;
    }

Tip:此处参数useProxy为数据库获取到的配置所以使用String类型,根据需要改为boolean类型可能更合适

三、使用

public static void main(String[] args) {
       	// CloseableHttpClient httpClient = new ProxyTest().buildHttpClient("true", "10.10.122.33", "9000");
        CloseableHttpClient httpClient = new ProxyTest().buildHttpClient("false", null, null);
        try {
            HttpGet httpGet = new HttpGet("http://baidu.com");
            CloseableHttpResponse response = httpClient.execute(httpGet);
            String resp;
            try {
                HttpEntity entity = response.getEntity();
                resp = EntityUtils.toString(entity, "UTF-8");
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

最后

以上就是感动世界最近收集整理的关于HttpClient使用代理的全部内容,更多相关HttpClient使用代理内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部