網上也有一些文章但是大多數涉及帶有授權驗證的proxy都有問題,主要問題就是出在對Authenticator.setDefault的使用,以及base64編碼的問題上代碼是最沒有二義性的文檔,實現原理不再解釋,請看代碼去體會。
ackage 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 [email protected]
*/
ublic class ProxyConnTest {
ublic static void initProxy(String host, int port, final String username,
final String passWord) {
Authenticator.setDefault(new Authenticator() {
rotected PasswordAuthentication getPassWordAuthentication() {
return new PassWordAuthentication(username,
ew 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\");
}
ublic 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();
}
}