网上也有一些文章但是大多数涉及带有授权验证的proxy都有问题,
主要问题就是出在对 authenticator.setdefault的使用,以及base64编码的问题上
代码是最没有二义性的文档,实现原理不再解释,请看代码去体会。
如果转载请注明代码出处。
chimae@cnjsp.org
package org.chimae.net;
import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.authenticator;
import java.net.httpurlconnection;
import java.net.passwordauthentication;
import java.net.url;
/**
* @author chimae@cnjsp.org
*/
public class proxyconntest {
public static void initproxy(string host, int port, final string username,
final string password) {
authenticator.setdefault(new authenticator() {
protected passwordauthentication getpasswordauthentication() {
return new passwordauthentication(username,
new string(password).tochararray());
}
});
system.setproperty("http.proxytype", "4");
system.setproperty("http.proxyport", integer.tostring(port));
system.setproperty("http.proxyhost", host);
system.setproperty("http.proxyset", "true");
}
public static void main(string[] args) throws ioexception {
string url = "http://java.sun.com/";
string proxy = "yourproxy";
int port =8080;
string username ="username";
string password ="password";
string curline = "";
string content = "";
url server = new url(url);
initproxy(proxy,port,username,password);
httpurlconnection connection = (httpurlconnection)server.openconnection();
connection.connect();
inputstream is = connection.getinputstream();
bufferedreader reader = new bufferedreader(new inputstreamreader(is));
while ((curline = reader.readline()) != null) {
content += curline;
}
system.out.println("content= " + content);
is.close();
}
}
