2011-12-07 40 views
3

我正在嘗試使用URL連接庫編寫一個連接到Twitter搜索URL(它返回一個JSON推文列表)的小型java程序。通過代理連接到Java中的URL

我這是從Java教程所採取的代碼如下所示:

 public static void main(String[] args) throws Exception { 
     URL oracle = new URL("http://search.twitter.com/search.json?q=hi"); 
     URLConnection yc = oracle.openConnection(); 
     BufferedReader in = new BufferedReader(
           new InputStreamReader(
           yc.getInputStream())); 
     String inputLine; 

     while ((inputLine = in.readLine()) != null) 
      System.out.println(inputLine); 
     in.close(); 
    } 

,但由於某種原因,我不斷收到以下異常:

in thread "main" java.net.ConnectException: Connection refused 
    at java.net.PlainSocketImpl.socketConnect(Native Method) 

我不知道這是什麼由於我寫代碼的方式,eclipse設置或者與我的網絡有關的東西。我的代理服務器配置了Internet訪問。據我所知這是正確配置,因爲我得到更新,並可以通過eclipse安裝新軟件。我是否需要將代理信息以某種方式放在URL方法中,或者是其他問題。

回答

4

URL依賴於代理系統屬性,嘗試設置代理這樣的:

System.setProperty("http.proxyHost", "yourproxyserver"); 
System.setProperty("http.proxyPort", "portnumber"); 
+0

身份驗證呢? – Randnum

+0

所以對我來說這將是System.setProperty(「http.proxy.mycompany.com」,「我的公司」); – Randnum

+0

和System.setProperty(「http.8080」,「8080」);? – Randnum

4

不幸的是,在Eclipse中正確的代理設置似乎並沒有幫助代理Java程序在Eclipse中開始。同樣,將Java系統設置設置爲使用全系統代理設置也不會。不管什麼時候你有一個需要認證的代理。

正如托馬斯·約翰·Eggum說,如果你有那麼一個「正常的」非認證代理通過-D設置兩個JVM變量http.proxyHosthttp.proxyPort無論是在命令行或編程(見下文)將處理後事。

對於驗證代理服務器,即想要查看用戶標識和密碼的服務器,很多人推薦設置http.proxyUserhttp.proxyPassword。這是不好的建議,因爲這些都不起作用。顯然它們是在Java文檔中定義的而不是

不幸的是,它看起來像「做」身份驗證的方式是使用身份驗證器,以編程方式。如果你打算這麼做,那麼你也可以通過編程來完成整個事情,例如包括主機和端口。下面是我如何工作:

public static void main(String[] args) { 
     try { 

     System.setProperty("http.proxyHost", "my.proxy.host"); 
     System.setProperty("http.proxyPort", "8080-or-whatever-proxy-port"); 
     Authenticator.setDefault(new DummyAuthenticator()); 

     /* do your main program stuff */    

     } catch (Exception e) { 
     e.printStackTrace(); 
     } 
    } 

    private static class DummyAuthenticator extends Authenticator { 
     public PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(
       "my-user-id", "my-password".toCharArray() 
       ); 
     } 
    } 
+0

這有效,更詳細,包括用戶名/密碼認證。 – sversch