Authenticator.setDefault() 全局生效,需線程安全。sun.misc.BASE64Encoder(不推薦)。import java.io.*;
import java.net.*;
import java.util.Base64;
public class ProxyConnTest {
public static void initProxy(String host, int port, final String user, final String pwd) {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pwd.toCharArray());
}
});
System.setProperty("http.proxyHost", host);
System.setProperty("http.proxyPort", String.valueOf(port));
System.setProperty("http.proxySet", "true");
// HTTPS 另需設置 https.proxyHost/Port
}
public static void main(String[] args) throws IOException {
String url = "https://java.sun.com/";
String proxy = "your.proxy.host";
int port = 8080;
String user = "username";
String pwd = "password";
initProxy(proxy, port, user, pwd);
URL server = new URL(url);
HttpURLConnection conn = (HttpURLConnection) server.openConnection();
conn.connect();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
PasswordAuthentication 構造函數接受 char[] 密碼,比 String 更安全。http.proxyHost/Port/Set 必須在建立連接前設置。https.proxyHost、https.proxyPort,且可能涉及 SSL 憑證驗證。socksProxyHost/Port。static String encodeBase64(String input) {
return new String(Base64.getEncoder().encode(input.getBytes("UTF-8"))); // JDK 8+
// JDK 7: 使用 Apache Commons Codec 或自寫 Base64 編碼器
}
若不使用 Authenticator,可手動設置 Proxy-Authorization 請求頭:
String auth = user + ":" + pwd;
String encoded = Base64.getEncoder().encodeToString(auth.getBytes());
conn.setRequestProperty("Proxy-Authorization", "Basic " + encoded);