企業內網常透過代理伺服器管控外部存取。Java 應用若不支援代理,將無法呼叫外部 API、下載資源。本文詳述 JVM 系統屬性配置、程式碼動態設定、各類代理協定與認證處理。
System.setProperty("proxySet", "true");
System.setProperty("proxyHost", "proxy.mycompany.com");
System.setProperty("proxyPort", "8080");
須在建立任何 URL/HttpURLConnection 之前 設定,建議在 `main()` 或靜態初始化塊最前端執行。
String userPass = "username:password";
String encoded = "Basic " + Base64.getEncoder().encodeToString(userPass.getBytes(StandardCharsets.UTF_8));
URL url = new URL("https://java.sun.com/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Proxy-Authorization", encoded);
注意:JDK 1.1.x 需手工加 Basic 前綴;JDK 1.2+ `Authenticator.setDefault()` 可全域自動處理。
System.setProperty("ftpProxySet", "true");
System.setProperty("ftpProxyHost", "proxy.mycompany.com");
System.setProperty("ftpProxyPort", "8080");
// 之後即可直接 new URL("ftp://ftp.example.com/file.txt") 存取
System.setProperty("socksProxySet", "true");
System.setProperty("socksProxyHost", "socks.mycompany.com");
System.setProperty("socksProxyPort", "1080"); // SOCKS 預設埠
適用於非 HTTP 協定(如原生 Socket、RMI、JDBC 連線)穿透防火牆。
| 版本 | 已知問題 | 解法 |
|---|---|---|
| JDK 1.1.7 (WebSphere 3.0) | 系統屬性無效,`getInputStream()` 逾時或找不到主機 | 使用 `new URL(protocol, host, port, file, handler)` 手工指定代理主機/埠 |
| JDK 1.2+ | 無 | 優先使用 `Authenticator` + 系統屬性 |