2013-02-19 36 views
1

我在試圖用Java編寫JSoup網頁抓取工具的公司網絡上,我似乎無法連接。任何方式來啓用通過防火牆的網頁抓取?

要測試一下,當我運行下面的代碼時,它給了我一個java.netConnectException:Connection refused。

Socket socket = null; 
    try { 
     socket = new Socket("google.com", 80) 
     System.out.println("it works!"); 
    } finally {    
     if (socket != null) try { socket.close(); } catch(IOException e) {} 
    } 

爲了記錄在案,我JSoup代碼如下所示:

Connection con = Jsoup.connect("http://en.wikipedia.org/wiki/Main_Page"); 
    Document doc = con.get(); 

當我獨自運行它,它給了我一個超時異常(甚至alotting它慷慨超時後)。我應該怎麼做才能使其在我的網絡中正常工作?

+1

您是否試過使用Google搜索JSoup和Proxy? – 2013-02-19 15:54:08

+0

讓我們從頭開始。您是否可以直接訪問計算機上的Internet或使用公司網絡代理? – vacuum 2013-02-19 16:05:19

+0

不,端口80將不會在公司環境中廣泛開放。在Internet Explorer中,轉至工具 - > Internet選項。左鍵單擊連接選項卡。左鍵單擊LAN設置按鈕。在LAN設置對話框的底部,將是您需要放入Java代碼的代理信息。 – 2013-02-19 16:05:55

回答

2

我找到了一個解決方案:I had to simply find my proxy and set it in my code.

// if you use https, set it here too 
System.setProperty("http.proxyHost", "<proxyip>"); // set proxy server 
System.setProperty("http.proxyPort", "<proxyport>"); // set proxy port 

Document doc = Jsoup.connect("http://your.url.here").get(); // Jsoup now connects via proxy 

此外,您可能需要set the user agent。我在那裏留下了「引用者」代碼,儘管我認爲在大多數情況下並不需要。請注意,userAgent由您正在訪問的Web服務器歧視計算機而構成。

doc = Jsoup.connect("https://www.facebook.com/") 
    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6") 
    .referrer("http://www.google.com") 
    .get();