查询谷歌距离矩阵api时出错

时间:2013-04-14 23:52:13

标签: android xml api

我正在尝试调用google distance matrix 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 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;

任何帮助都是值得赞赏的。

1 个答案:

答案 0 :(得分: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();
            }
        }
     }

它成功运作。