当我在使用Java.net包的API时,由于公司的网络设置了都是通过代理访问网络,因此每次都是遇到connection timeout的情况
针对这种情况,我查看了资料,和JDK的API,发现使用java.net.Proxy类可以设置通过代理访问外网,但访问外网的过程中必须通过验证才行,通过验证使用的类是Authenticator类
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class BasicAuthenticator extends Authenticator{
String username;
String password;
public BasicAuthenticator(String userName,String password){
this.username = userName;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password.toCharArray());
}
}
定义BasicAuthenticator继承Authenticator抽象类,需要重写getPasswordAuthentication()方法,
应用程序通过重写子类中的 getPasswordAuthentication()
使用此类。此方法通常使用各种 getXXX() 访问器方法获取关于请求验证的实体的信息。然后,它必须通过与用户交互或者某些其他非交互手段获取用户名和密码。之后凭据将以 PasswordAuthentication
返回值的形式返回。
PasswordAuthentication 类是供 Authenticator 使用的数据持有者。它只是用户名和密码的存储库。
<span style="white-space:pre"> </span>InetSocketAddress addr = new InetSocketAddress("10.200.100.81",8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP,addr);
Authenticator.setDefault(new BasicAuthenticator("name","password"));
URL url = new URL("http://www.csdn.net/");
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(proxy);
urlConn.connect(); //打开到url引用资源的通信连接
urlConn.setConnectTimeout(5000);
long size = urlConn.getContentLength();
InputStream is = urlConn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br =new BufferedReader(isr);
while(true){
String s = br.readLine();
if(s!=null){
sop(s);
}
}
使用代理的时候,这里使用的是Proxy.Type.HTTP方式,
还要通过Authentictor.setDefault方法将帐号与密码传过来,这样代理及验证都可以通过了。