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

数据采集,爬虫等可能需要用到代理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();
        }

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

你可能感兴趣的:(技术文章)