在使用 URLConnection 獲取網絡文件流(即下載文件)時,遇到了服務器不允許連外網的情況,因此需要爲 URLConnection 設置代理才能訪問外網資源。
本文內容關於爲 URLConnection 設置代理
// 創建URL
URL url = new URL(filePath);
// 創建代理服務器
InetSocketAddress addr = new InetSocketAddress("10.255.254.225", 3128);
// http 代理
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
// 試圖連接並取得返回狀態碼
URLConnection urlconn = url.openConnection(proxy);
//以下三行是在需要驗證時,輸入帳號密碼信息
String headerkey = "Proxy-Authorization";
Base64 base64 = new Base64();
//帳號密碼用:隔開,base64加密方式
String headerValue = "Basic "+ base64.encodeToString(":".getBytes());
urlconn.setRequestProperty(headerkey, headerValue);
urlconn.connect();
HttpURLConnection httpconn = (HttpURLConnection) urlconn;
httpResult = httpconn.getResponseCode();
if (httpResult != HttpURLConnection.HTTP_OK) {
log.error("無法連接到" + filePath);
} else {
// 取數據長度
int filesize = urlconn.getContentLength();
return urlconn.getInputStream();
}
以上代碼是使用 URLConnection 通過代理獲取外網地址的文件流並返回。
其中核心代碼:
1. 定義代理
// 創建代理服務器
InetSocketAddress addr = new InetSocketAddress("10.255.254.225", 3128);
// http 代理
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
// 試圖連接並取得返回狀態碼
2. 使用代理打開連接
URLConnection urlconn = url.openConnection(proxy);
3. 爲 URLConnection 設置代理授權信息(用戶名密碼等)
//以下三行是在需要驗證時,輸入帳號密碼信息
String headerkey = "Proxy-Authorization";
Base64 base64 = new Base64();
//帳號密碼用:隔開,base64加密方式
String headerValue = "Basic "+ base64.encodeToString(":".getBytes());
urlconn.setRequestProperty(headerkey, headerValue);
至此,爲 URLConnection 設置代理的工作已經完成了,後續正常使用即可。