2016-09-18 52 views
0

我想使用jsoup/java來訪問基於用戶輸入的主題的谷歌新聞文章。當我嘗試訪問谷歌新聞網頁,但是,我得到一個運行時錯誤這條線:Java - Jsoup HTTP錯誤獲取URL

try { 
doc = (org.jsoup.nodes.Document) Jsoup.connect("https://www.google.com/search?hl=en&gl=us&tbm=nws&authuser=0&q="+ "technology").get(); 
         } catch (IOException e1) { 
          // TODO Auto-generated catch block 
          e1.printStackTrace(); 
         } 

當我執行這個代碼,我得到這個錯誤:

org.jsoup.HttpStatusException: HTTP error fetching URL. Status=403, URL=https://www.google.com/search?hl=en&gl=us&tbm=nws&authuser=0&q=technology 
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:590) 
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:540) 
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:227) 
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:216) 
at newsbot.NewsBot.onUpdateReceived(NewsBot.java:93) 
at org.telegram.telegrambots.updatesreceivers.BotSession$HandlerThread.run(BotSession.java:197) 

但是,如果我輸入link到谷歌,我想接取的網頁完全apears。我非常感謝你的幫助,謝謝。

+0

你可以添加-Djavax。 net.debug =全部查看詳細日誌。這應該有助於調試。 –

回答

0

您需要包括用戶代理:

Jsoup.connect("https://www.google.com/search?hl=en&gl=us&tbm=nws&authuser=0&q="+ "technology") 
    .userAgent("blah-blah") 
    .get(); 
0

可以包括用戶代理,這樣的頁面不會被禁止(HTTP 403)

Document doc = (Document) Jsoup 
       .connect("https://www.google.com/search?hl=en&gl=us&tbm=nws&authuser=0&q=" + "technology") 
       .ignoreContentType(true) 
       .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0").get(); 
     System.out.println(doc);