为什么Google Maps静态API无法处理我编码的URI?

时间:2010-09-19 09:14:16

标签: java google-maps

我正在尝试使用Google Maps静态API将一些Google地图位集成到我的Java Web应用程序中。目前我只想获得一张地图,任何地图。他们的例子:

http://maps.google.com/maps/api/staticmap?center=40.714728,-73.998672&zoom=12&size=400x400&sensor=false

从我的浏览器正常工作。但是我使用的Java HTTP客户端软件(Apache的http组件版本4.0.2)坚持我编码我的URI,所以我最终得到了这个:

http://maps.google.com/maps/api/staticmap?center%3D40.714728%2C-73.998672%26zoom%3D12%26size%3D400x400%26sensor%3Dfalse

哪个不起作用。我很乐意不编码我的URI,但如果不这样做,Apache客户端就会失败。所以我的问题是我怎么能:

  • 说服Apache的客户端使用普通URI或
  • 将已编码的URI转换为Google将接受的表单

2 个答案:

答案 0 :(得分:1)

仅编码URI的参数。您的第一个?,然后您的=&不应该是URI编码。

你的URI应该是

http://maps.google.com/maps/api/staticmap?center=40.714728%2C-73.998672&zoom=12&size=400x400&sensor=false

唯一的URI编码字符为%2C,坐标之间为,

答案 1 :(得分:0)

正如Pekka建议你需要离开&=未编码。

您的已编码网址

http://maps.google.com/maps/api/staticmap?center%3D40.714728%2C-73.998672%26zoom%3D12%26size%3D400x400%26sensor%3Dfalse

vs未编码的&%26)和=%3D)(工作)

http://maps.google.com/maps/api/staticmap?center=40.714728%2C-73.998672&zoom=12&size=400x400&sensor=false

Apache的HTTPComponents HTTP客户端有很多接口,您可以使用它们构建请求URL。为了确保URL的正确部分已编码,我建议使用此方法:

List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("center", "40.714728,-73.998672"));
qparams.add(new BasicNameValuePair("zoom", "12"));
qparams.add(new BasicNameValuePair("size", "400x400"));
qparams.add(new BasicNameValuePair("sensor", "false"));
URI uri = URIUtils.createURI("http", "maps.google.com", -1, "/maps/api/staticmap", 
    URLEncodedUtils.format(qparams, "UTF-8"), null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
  1. 更多示例http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
  2. API文档http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html