网上也有一些文章但是大多数涉及带有授权验证的proxy都有问题,主要问题就是出在对authenticator.setdefault的使用,以及base64编码的问题上代码是最没有二义性的文档,实现原理不再解释,请看代码去体会。如果转载请注明代码出处。
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();
}
}
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器