各位大大再開發的時候多少有以下的經驗吧
要如何從內部網路藉由代理伺服器(Proxy)出去外網取得相關資源
如果沒設定好不管如何去執行都只會得到UnKnowHost這錯誤訊息吧
在此紀錄說明
以下當然有少很多說明
特別是 Proxy 機制
有興趣可以查維基百科
一般網路:
Local - 數據機 - Internet
企業( 特殊 ) 網路:
Local - Proxy - Internet
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
public class TestProxy {
	public final static String acc = "A123456789";
	public final static String pwd = "!QAZ2wsx";
	public static void main(String[] args) {
		Authenticator.setDefault(new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// TODO Auto-generated method stub
				return new PasswordAuthentication(acc, pwd.toCharArray());
			}
		});
		System.setProperty("http.proxyHost", "proxy.com.tw");
		System.setProperty("http.proxyPort", "80");
		System.setProperty("https.proxyHost", "proxy.com.tw");
		System.setProperty("https.proxyPort", "80");
		URL url;
		try {
			url = new URL("https://tw.yahoo.com/");
			URLConnection connection = url.openConnection();
			InputStream is = connection.getInputStream();
			int i;
			while ((i = is.read()) != -1) {
				System.out.print((char)i);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
			
		} catch (IOException e) {
			e.printStackTrace();
			
		}
	}
}
沒有留言:
張貼留言