您的位置:首页 > 理论基础 > 计算机网络

Java Http连接中(HttpURLConnection)中使用代理(Proxy)及其验证(Authentication)

2013-03-18 22:10 716 查看
使用Java的HttpURLConnection类可以实现HttpClient的功能,而不需要依赖任何其他类库。所有有时候大家就直接使用它来完成一些简单(或复杂)的功能。但是你活在伟大的{print G.F.W}后面,如果你需要访问的网站被墙了,那HttpURLConnection类就会出现连接超时的错误。这时候就需要给他设置代理(Proxy)了。

设置代理(Proxy)可以有两种方式:

1、通过设置系统属性(System.setPropery(String key, String value)的方式

首先你可以在这里看到Java支持的属性。我们可以使用其中的http.proxyHost,http.proxyPort这两个属性。顾名思义,就是分别设置代理服务器地址和代理端口。

//在你发起Http请求之前设置一下属性

//通知Java您要通过代理进行连接
System.getProperties().put("proxySet", "true");

//指定代理所在的服务器
System.getProperties().put("proxyHost", "127.0.0.1");

//指定代理监听的端口
System.getProperties().put("proxyPort", "8580");


  或者

System.setProperty("http.proxyHost", "www.proxy.com");
System.setProperty("http.proxyPort", "8080");


  

替换上面的www.proxy.com为你的代理服务器地址或IP地址,以及相应的端口为真实端口,Http连接及可以工作了。需要注意的是如果你设置了这些属性,那么所有的Http请求都会通过代理服务器。这些属性是JVM级别的,设置了以后对所有的同类请求都有效。比如上面的是关于http的,还有关于ftp的等等。

如果你的代理服务器不需要验证,那到此就结束了。但一般都是需要验证的。但是你要是看了上面Java支持的属性列表,你就会发现那里面并没有期望中的

http.proxyUserName=username

http.proxyPassword=password

publicclass BasicAuthenticator extends Authenticator {

String userName;

String password;

public BasicAuthenticator(String userName, String password) {

this.userName = userName;

this.password = password;

}

/**

* Called when password authorization is needed.  Subclasses should

* override the default implementation, which returns null.

*

* @return The PasswordAuthentication collected from the

*         user, or null if none is provided.

*/

@Override

protected PasswordAuthentication getPasswordAuthentication() {

returnnew PasswordAuthentication(userName, password.toCharArray());

}

}

我们需要覆盖java.net.Authenticator类的getPasswordAuthentication()方法,并返回一个PasswordAuthentication实例。要使他起作用,还需要设置

Authenticator.setDefault(new BasicAuthenticator(userName, password));

Authenticator.setDefault(new BasicAuthenticator(userName, password));


这样就提供了基于Http Basic的验证,接着就可以顺畅的使用需要验证的代理了。

2、通过java.net.Proxy类。

这种方式是实例化一个Proxy类提供代理服务器的信息,如端口和地址。

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));

URLConnection conn = url.openConnection(proxy);

//格式如:  "Proxy-Authorization"= "Basic Base64.encode(user:password)"

String headerKey = "Proxy-Authorization";

String headerValue = "Basic " + Base64.encode(user+":"+password);

conn.setRequestProperty(headerKey, headerValue);

//..........

//格式如下:
"Proxy-Authorization"= "Basic Base64.encode(user:password)"
String headerKey = "Proxy-Authorization";
String headerValue = "Basic " + Base64.encode(user+":"+password);
conn.setRequestProperty(headerKey, headerValue);

//..........


其中的Base64.encode(user:password)是指把用户名和密码用冒号连接起来之后使用Base64编码后的值作为值的一部分。

通过这种方式只影响特定的Http连接,但是需要对代码进行修改。这种方式下是否可以使用Authenticator还未做验证。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐