2013-04-14 79 views
0

我想打電話給谷歌距離矩陣API,但在這裏115得到一個錯誤是非法的查詢是我的代碼:錯誤在查詢谷歌距離矩陣API

protected Document doInBackground(LatLng... latlng) { 

     String destinationURL = ""; 
     // ASSUMING THAT FIRST LATLNG PASSED IS ALWAYS A SOURCE LOCATION 
     for(int index = 1; index < latlng.length; index ++) 
     { 
      destinationURL += latlng[index].latitude +"," + latlng[index].longitude; 
      if(index+1 != latlng.length) 
      { 
       destinationURL+= "|"; 
      } 
     } 
     String url = "http://maps.googleapis.com/maps/api/distancematrix/xml?" 
       + "origins=" + latlng[0].latitude + "," + latlng[0].longitude 
       + "&destinations=" + destinationURL 
       + "&sensor=false&mode=walking"; 

如果我粘貼上面則給出的網址這是結果:URL link of query

錯誤的詳細信息:java.lang.IllegalArgumentException: Illegal character in query at index 115: http://maps.googleapis.com/maps/api/distancematrix/xml?origins=35.777418,-78.677666&destinations=35.78036,-78.67816|35.787515,-78.670456&sensor=false&mode=walking

代碼調用上述網址:

try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpContext localContext = new BasicHttpContext(); 
      HttpPost httpPost = new HttpPost(url); 
      HttpResponse response = httpClient.execute(httpPost, localContext); 
      InputStream in = response.getEntity().getContent(); 
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
      Document doc = builder.parse(in); 
      return doc; 

任何幫助v.much讚賞。

+1

把它扔進瀏覽器的作品。 | |需要編碼到%7C? –

+0

我不確定,我在android應用程序中使用它,它崩潰在:HttpPost httpPost = new HttpPost(url);.完全卡住了 – Rohit

+0

你是對的@加布塞尚。我只注意到「|」管道字符在URLencoder.encode(|)後轉換爲%7C。當你說如果|時我沒有第一次需要編碼到%7C中,但現在可以理解了 – Rohit

回答

3

經過幾次嘗試後發現此問題。我正在使用管道字符「|」加入經緯度。注意管道字符只是一個字符串。 但是爲了在網址中使用添加豎線URLEncoder的最終的字符串添加:

destinationURL += latlng[index].latitude +"," + latlng[index].longitude; 
if(index+1 != latlng.length) 
    { 
     try { 
      destinationURL+= URLEncoder.encode("|", "UTF-8"); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

它成功合作。