HttpClient配置代理


代码及注释

//要访问的网址
String url = "http://www.baidu.com";
try {
//设置代理的 IP、端口号、协议(替换自己的)
HttpHost proxy = new HttpHost("自己的代理Ip",代理的端口号,"http");
//设置要访问的HttpHost,即目标站点的HttpHost。 IP、端口号、协议(替换自己的)
HttpHost target = new HttpHost("www.baidu.mn",80,"http");

//设置认证
CredentialsProvider provider = new BasicCredentialsProvider();
//第一个参数对应代理httpHost,第二个参数设置代理的用户名和密码,如果代理不需要用户名和密码,填空
provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials("代理用户名", "代理密码"));
//实例化CloseableHttpClient对象
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
//把代理设置到请求配置里
RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();

//创建请求实例
HttpGet get = new HttpGet(url);
//将配置设置到请求实例中,如果还有请求头信息,自行设置
get.setConfig(requestConfig);
//发送请求并获得相应
CloseableHttpResponse res = httpClient.execute(target,get);
//获取响应码
int statusCode = res.getStatusLine().getStatusCode();
//将响应内容转化为String字符串
String result = EntityUtils.toString(res.getEntity());

} catch (ClientProtocolException e) {
LOGGER.info("异常"+e);
} catch (IOException e) {
LOGGER.info("异常"+e);
}