Httpclient通过代理访问网络

来源:互联网 发布:古典吉他 知乎 编辑:程序博客网 时间:2024/05/20 13:08

httpClient通过代理(Http Proxy)进行请求,在浏览一些网站的时候由于各种原因,无法进行访问。这时我们需要通过IE,FireFox进行Http的代理设置,httpclient也可以模拟浏览器的代理的相关设置。

Httpclient有两种代理使用模式,一种是使用匿名代理采用抢先占用的方式,另外一种是需要提供用户名和密码认证的代理机制。

匿名代理的抢先占用的方式,有时候使用不当,会把所有的代理资源耗光,在一般情况下,不推荐使用。

4.x版本的httpClinet功能比以前更加强大,使用方式也不一样,下面是一个基于4.x版本的用例,提供需要验证用户名和密码的代理。  

 

packagetest.ffm83.commons.httpClient;

 

importorg.apache.commons.lang.StringUtils;

importorg.apache.http.HttpHost;

importorg.apache.http.auth.AuthScope;

importorg.apache.http.auth.UsernamePasswordCredentials;

importorg.apache.http.client.CredentialsProvider;

importorg.apache.http.client.config.RequestConfig;

importorg.apache.http.client.methods.CloseableHttpResponse;

importorg.apache.http.client.methods.HttpGet;

importorg.apache.http.impl.client.BasicCredentialsProvider;

importorg.apache.http.impl.client.CloseableHttpClient;

importorg.apache.http.impl.client.HttpClients;

importorg.apache.http.util.EntityUtils;

 

/* 通过需要认证的代理服务器访问网络

 * 使用httpClient 4.x版本实现

 * 作者:范芳铭

 * */

public class EasyExecuteProxy {

      public static voidmain(String[] args)throwsException {

             CredentialsProvider credsProvider = new BasicCredentialsProvider();

             credsProvider.setCredentials(

                     new AuthScope("192.168.1.1", 80), //代理服务器信息

                     new UsernamePasswordCredentials("fanfangming","123456")); //代理服务器

             CloseableHttpClient httpclient =HttpClients.custom() //构建需要认证的httpclient

                    .setDefaultCredentialsProvider(credsProvider).build();

             try {

                 HttpHost target = new HttpHost("www.verisign.com", 443,"https"); //目标网站

                 HttpHost proxy = new HttpHost("192.168.19.9", 80);

 

                 RequestConfig config =RequestConfig.custom()

                     .setProxy(proxy)

                     .build();

                 HttpGet httpget = new HttpGet("/");

                 httpget.setConfig(config);

 

                 System.out.println(StringUtils.center("通过代理 "+ proxy, 50,"-"));

                 System.out.println(StringUtils.center("进行网络访问"+ target, 50,"-"));

                 CloseableHttpResponse response =httpclient.execute(target, httpget);

                 try {

                     System.out.println(response.getStatusLine());

                     EntityUtils.consume(response.getEntity());

                 } finally {

                     response.close();

                 }

             } finally {

                 httpclient.close();

             }

         }

}

 

运行结果:

HTTP/1.1 200 就已经能正常访问网络了。

0 0
原创粉丝点击