2011-09-20 30 views
5
String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false"; 

     URL google = new URL(url); 
     HttpURLConnection con = (HttpURLConnection) google.openConnection(); 

不錯,我用的BufferedReader打印的內容,我得到403錯誤403錯誤在訪問的URL,但工作在瀏覽器

相同的URL在瀏覽器中正常工作。任何人都可以建議。

回答

2

HTTP 403禁止狀態碼。您必須閱讀HttpURLConnection.getErrorStream()以查看服務器的響應(可以告訴您爲什麼您已獲得HTTP 403),如果有的話。

+0

下面是如何讀取錯誤流:http://stackoverflow.com/a/9129991/10592你需要調用getErrorStream前connection.getResponseCode()()會工作。 –

+0

@Tim Coope,當你發佈** I **發佈的答案時,這很有趣。 –

0

大多數瀏覽器在輸入URL時會自動對URL進行編碼,但Java URL函數不會。 你應該用URLEncoder對URL進行編碼URL Encoder

2

這段代碼應該可以正常工作。如果您一直在提出一些要求,Google可能會扼殺您。我曾看過谷歌之前這樣做。您可以嘗試使用代理進行驗證。

+0

http://code.google.com/p/gmaps-api-issues/issues/detail?id=1933 – lds23

5

它工作在一個瀏覽器的原因,但不是在Java代碼瀏覽器會添加一些您在Java代碼中缺少的HTTP標頭,並且服務器需要這些標頭。我一直處於相同的情況 - 這個URL在Chrome和Chrome插件「簡單REST客戶端」中都可以使用,但在Java中不起作用。在getInputStream()解決問題之前添加此行:

   connection.addRequestProperty("User-Agent", "Mozilla/4.0"); 

..儘管我從來沒有使用過Mozilla。您的情況可能需要不同的標題。它可能與cookies有關......我在錯誤流中獲取了文本,建議我啓用cookie。

請注意,您可能會通過查看錯誤文本獲取更多信息。這裏是我的代碼:

 try { 
      HttpURLConnection connection = ((HttpURLConnection)url.openConnection()); 
      connection.addRequestProperty("User-Agent", "Mozilla/4.0"); 
      InputStream input; 
      if (connection.getResponseCode() == 200) // this must be called before 'getErrorStream()' works 
       input = connection.getInputStream(); 
      else input = connection.getErrorStream(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
      String msg; 
      while ((msg =reader.readLine()) != null) 
       System.out.println(msg); 
     } catch (IOException e) { 
      System.err.println(e); 
     } 
相關問題