views:

32

answers:

2

I'm trying to integrate some Google maps bits into my Java web app using the Google Maps static API. For the moment I'm just trying to get a map, any map. Their example:

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

works fine from my browser. However the Java HTTP client software I am using (the one from Apache's http components, version 4.0.2) insists that I encode my URIs, so I end up with this:

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

which doesn't work. I would happily not encode my URIs but the Apache client fails if I don't. So my question is how can I either:

  • persuade Apache's client to use the plain URI or
  • get the encoded URI into a form Google will accept

?

+1  A: 

Only encode the parameters of the URI. Your first ?, then your = and your & shouldn't be URI encoded.

Your URI should be

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

The only URI-encoded character is %2C, the , between your coordinates.

Vivien Barousse
Thanks! Correct answer.
HenryTyler
A: 

As Pekka suggested you need to leave to & and = unencoded.

Your encoded url

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

vs unencoded & (%26) and = (%3D) (working)

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

Apache's HTTPComponents HTTP Client has a lot of interfaces with which you can build your request URL. To make sure that the proper parts of the URL are encoded I would suggest using this method:

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. More example http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
  2. API Docs http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html
adamse
Awesome, thanks!
HenryTyler
Just simple rule, always encode param name and value. adamse have given a nice example.
Ashish Patil