[原創(chuàng)]通過HttpURLConnection如何使用代理服務(wù)器連接公網(wǎng)
--sunfruit在openConnection之前加上
Properties prop = System.getProperties();
System.getProperties().put("proxySet","true");
// 設(shè)置http訪問要使用的代理服務(wù)器的地址
prop.setProperty("http.proxyHost","xxxxxxx");
// 設(shè)置http訪問要使用的代理服務(wù)器的端口
prop.setProperty("http.proxyPort","xxxxx");
然后并不像有的貼子說的那樣添加
prop.setProperty("http.proxyUser","xxxxxxxx");
prop.setProperty("http.proxyPassword","xxxxx");
添加這樣的內(nèi)容是不行的,而是將"username:password"進(jìn)行base64編碼,具體代碼如下
String authentication = "username:password";
String encodedLogin = new BASE64Encoder().encode(authentication.getBytes());
httpurlconnection.setRequestProperty("Proxy-Authorization", " Basic " + encodedLogin);
注意BASE64Encoder().encode(authentication.getBytes());這里不能使用BASE64Encoder().encodeBuffer(authentication.getBytes())否則報錯
具體原因參考sun公布的JDK BUG , Bug ID: 4615330 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4615330
posted on 2007-03-22 10:41 sunfruit 閱讀(1785) 評論(0) 編輯 收藏 所屬分類: JAVA SE & EE