HttpClient代理服务器配置

使用代理服务器最简单的方式就是,指定一个默认的proxy参数。

HttpHost proxy = new HttpHost("someproxy", 8080);

DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

CloseableHttpClient httpclient = HttpClients.custom()

        .setRoutePlanner(routePlanner)

        .build();


 

我们也可以让HttpClient去使用jre的代理服务器。

SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(

        ProxySelector.getDefault());

CloseableHttpClient httpclient = HttpClients.custom()

        .setRoutePlanner(routePlanner)

        .build();

 

又或者,我们也可以手动配置RoutePlanner,这样就可以完全控制Http路由的过程。

HttpRoutePlanner routePlanner = new HttpRoutePlanner() {

 

    public HttpRoute determineRoute(

            HttpHost target,

            HttpRequest request,

            HttpContext context) throws HttpException {

        return new HttpRoute(target, null,  new HttpHost("someproxy", 8080),

                "https".equalsIgnoreCase(target.getSchemeName()));

    }

 

};

CloseableHttpClient httpclient = HttpClients.custom()

        .setRoutePlanner(routePlanner)

        .build();

    }

}


可以封装成一个方法来获取一个proxyHttpClient实例:

public static CloseableHttpClient getProxyHttpClient(IP ip){
		HttpHost proxy=new HttpHost(ip.getHost(),ip.getPort());
		DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
		CloseableHttpClient proxyHttpClient=HttpClients.custom().setRoutePlanner(routePlanner).build();
		return proxyHttpClient;
	}



 

你可能感兴趣的:(HttpClient)