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 就已经能正常访问网络了。
- Httpclient通过代理访问网络
- Httpclient通过代理访问网络
- c#通过代理访问网络
- Python 通过代理访问网络
- 通过HttpURLConnection和HttpClient访问网络
- Java通过网络代理访问网络
- Java 通过代理访问外部网络
- Java程序通过代理访问网络
- Java程序通过代理访问网络
- android通过 httpClient 的post访问 网络数据
- HttpClient网络访问
- HttpClient访问网络
- 使用HttpClient访问网络
- 使用HttpClient访问网络
- 19、HttpClient网络访问
- HttpClient 访问网络
- HttpClient 网络访问
- 网络访问之HttpClient
- Vb.net 调用Codesoft-LabelManager2 打印标签
- win2003关闭开机 服务控制管理器 在系统启动时至少有一个服务或驱动程序产生错误
- 基于百度翻译API开发属于自己的翻译工具
- 在Windows server 2008 中拒绝共享资源用户的本地登录
- 找出第K大的数<数组>
- Httpclient通过代理访问网络
- Matlab--------股票接口,获取股票数据
- JMM 指令重排
- 1、两人做游戏,轮流报数,报出的数只能是1、2、3、4、5、6、7、8其中之一,把两个人报出的数连加起来,谁报数后加起来的和是123,谁就获胜,让你先报,为了确保胜利,你第一个数报多少?
- Httpclient线程池的管理和利用
- Eclipse中Android公共库的正确建立及调用方法
- Linux最简单的网络通信
- 幸福生活每一天
- Apache && Nginx Log的配置