2012-04-02 110 views
0

我正在使用Google Maps API。當我使用以下URL並在瀏覽器中輸入時,我會彈出一個窗口,將JSON字符串保存爲記事本文件。從Google Maps API讀取JSON字符串

網址:https://maps.googleapis.com/maps/api/directions/json?origin=Bangalore,印度&目的地=貝爾高姆,印度&傳感器=假

...但是當我寫了下面這段代碼以編程方式做同樣的,有以下異常:

例外:

java.io.IOException: Server returned HTTP response code: 400 for URL: https://maps.googleapis.com/maps/api/directions/json?origin=Bangalore, India&destination=Belgaum, India&sensor=false 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) 
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source) 

代碼:

try { 
     url = new URL("https://maps.googleapis.com/maps/api/directions/json?origin=Bangalore, India&destination=Belgaum, India&sensor=false"); 
     try { 
      HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
      conn.connect(); 
      //InputStream is = conn.getInputStream(); 
      InputSource geocoderResultInputSource = new  
      InputSource(conn.getInputStream()); 

       // read result and parse into XML Document 
       try { 
       geocoderResultDocument = 

DocumentBuilderFactory.newInstance()。newDocumentBuilder()。parse(geocoderResultInputSource); catch(SAXException e){ e.printStackTrace(); (ParserConfigurationException e){ e.printStackTrace(); }

有誰知道我在這裏做什麼錯誤?

感謝 阿布舍克小號

回答

2

您需要刪除空格:

用途:

new URL("https://maps.googleapis.com/maps/api/directions/json?origin=Bangalore,India&destination=Belgaum,India&sensor=false"); 

相反的:

new URL("https://maps.googleapis.com/maps/api/directions/json?origin=Bangalore, India&destination=Belgaum, India&sensor=false"); 
+0

謝謝埃內斯托。那太完美了!你知道這樣的Google API調用是無限的嗎?我需要做這樣的無限通話。 – 2012-04-02 04:11:46

+1

選中此項:https://developers.google.com/maps/documentation/directions/#Limits – 2012-04-02 04:29:41