HttpClient4.5.3设置代理(Proxy)访问目标地址

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

数据采集,爬虫等可能需要用到代理IP来访问目标地址,以下代码为HttpClient4.5.3使用代理(Proxy)访问目标地址

        //设置代理IP、端口、协议(请分别替换)
        HttpHost proxy = new HttpHost("你的代理的IP", 8080, "http");

        //把代理设置到请求配置
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .build();

        //实例化CloseableHttpClient对象
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();

        //访问目标地址
        HttpGet httpGet = new HttpGet("http://www.baidu.com");

        //请求返回
        CloseableHttpResponse httpResp = httpclient.execute(httpGet);
        try {
            int statusCode = httpResp.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                System.out.println("成功");
            }
        } catch (Exception e) {

        } finally {
            httpResp.close();
        }

如果有什么不明白,可以留言给我!

展开阅读全文

没有更多推荐了,返回首页