0

我正在尝试调用谷歌距离矩阵 api,但在 115 处收到错误为非法查询。这是我的代码:

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,那么结果如下: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;

非常感谢任何帮助。

4

1 回答 1

3

经过几次尝试发现这里的问题。我正在使用管道字符“|” 用于加入经纬度。注意管道字符只是一个字符串。但是,为了在 URL 中添加管道字符,请使用 URLEncoder最终字符串添加:

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

它成功地工作了。

于 2013-04-15T02:41:35.120 回答