2011-11-16 38 views
11

我想在運行時使用代理創建url連接。我的代碼如下:如何在java中使用代理獲取URL連接?

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.10.100.100", 80)); 
HttpURLConnection connection = 
    (HttpURLConnection)new URL("http://abc.abcd.com").openConnection(proxy); 

但這不起作用。任何人都知道爲什麼?

+4

什麼是不工作?你得到一個StackTrace或一個錯誤? –

+2

爲什麼它不起作用?什麼是錯誤? – oers

+0

你正在使用什麼類型的代理? –

回答

13

添加答案爲今後遊客

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.10.100.100", 80)); 
HttpURLConnection connection =(HttpURLConnection)new URL("http://abc.abcd.com").openConnection(proxy); 
connection.setDoOutput(true); 
connection.setDoInput(true); 
connection.setRequestProperty("Content-type", "text/xml"); 
connection.setRequestProperty("Accept", "text/xml, application/xml"); 
connection.setRequestMethod("POST"); 
+0

感謝百萬它爲我工作:) – Vidhee

2

dku.rajkumar的方式不和我一起工作的幫助。

我嘗試這個,它的工作,但它需要兩倍的時間。

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.10.100.100", 80)); 

    HttpURLConnection connection = 
     (HttpURLConnection)new URL("http://abc.abcd.com").openConnection(proxy); 
    ((HttpURLConnection)new URL("http://abc.abcd.com").openConnection(proxy)).getInputStream(); 

System.out.println(connection.usingProxy()); 

結果爲真

沒有 ((HttpURLConnection)new URL("http://abc.abcd.com").openConnection(proxy)).getInputStream();

結果是假

相關問題