
為HttpURLConnection 建立代理連接
當嘗試確定HttpURLConnection 是否正在使用代理時,以下程式碼可能會錯誤地傳回false:
1 2 | conn = new URL(urlString).openConnection();
System.out.println( "Proxy? " + conn.usingProxy());
|
登入後複製
儘管透過代理伺服器連接,但仍會發生此行為。 Java 虛擬機器 (JVM) 通常會從作業系統設定中擷取代理資訊。但是,在某些情況下,JVM 可能不知道代理配置。
代理和 JVM 代理設定
為了確保 HttpURLConnection 使用適當的代理,有必要明確提供代理資訊。這可以透過建構一個Proxy 實例並將其傳遞給openConnection(proxy) 方法來實現:
1 2 3 | Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( "10.0.0.1" , 8080));
conn = new URL(urlString).openConnection(proxy);
|
登入後複製
驗證代理連接
如果代理需要身份驗證,則HttpURLConnection 將回應407 回應代碼。要解決此問題,可以如下設定身份驗證器:
1 2 3 4 5 6 7 8 | Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return ( new PasswordAuthentication( "user" ,
"password" .toCharArray()));
}
};
Authenticator.setDefault(authenticator);
|
登入後複製
以上是如何確保 HttpURLConnection 使用代理並處理驗證?的詳細內容。更多資訊請關注PHP中文網其他相關文章!