0

I'm using the following post method:

"myApiKey" stands for my google api key

public static void post(){
    try {
        Content resp = Request.Post("https://maps.googleapis.com/maps/api/geocode/json").bodyForm(Form.form().add("key",  "myApiKey").add("address",  "Sidney").build()).execute().returnContent();
        String response = resp.toString();
        System.out.println(response);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

In the method above, I have used fluent API(fluent API in the second grey box) The response is the following:

{
   "results" : [],
   "status" : "ZERO_RESULTS"
}

@v.ladyev, I have already solved the problem of places containing spaces on my own with such preprocessing:

public static String preprocessLocation(String location){
    String[] locationSplitted = location.split("\\s*,\\s*");
    StringBuilder query = new StringBuilder();
    for(int j = 0; j < locationSplitted.length; j++){
        if(j != 0){
            query.append("+");
        }
        String[] parts = locationSplitted[j].split(" ");
        for(int i = 0; i < parts.length; i++){
            query.append(parts[i]);
            if((i + 1) < parts.length){
                query.append("+");
            }
        }
        if((j + 1) < locationSplitted.length){
            query.append(",");
        }
    }
    return query.toString();
}

FOR THE ONES WHO WOULD LIKE TO APPEND OTHERS PARAMETERS or HEADERS (for instance, the key and the Accept-Language):

private static String post(String place){
        try {
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("address",place));
            parameters.add(new BasicNameValuePair("key", PUT_HERE_YOUR_KEY));
            URIBuilder builder = new URIBuilder("https://maps.googleapis.com/maps/api/geocode/json").setParameters(parameters);
            Content response = Request.Post(builder.build()).addHeader("Accept-Language", "en").execute().returnContent();
            return response.toString();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
StackUser
  • 587
  • 6
  • 26
  • What does the generated URL look like? This works for me: https://maps.googleapis.com/maps/api/geocode/json?address=Sidney – geocodezip Feb 11 '16 at 18:30
  • May be you shouldn't specify a fake API key. – v.ladynev Feb 11 '16 at 21:44
  • @v.ladynev I have put my real API key in my code. I have just put that apikey in the code to publish here. I thought it was obvious. I have specified it editing my question now – StackUser Feb 12 '16 at 00:12
  • @StackUser Your `preprocessLocation()` is incorrect, because of can be other non _alphanumeric characters_ in the geographic names, especially in other languages. – v.ladynev Feb 12 '16 at 16:43
  • @v.ladynev: so, your URIBuilder encode the language characters different from alphanumeric? – StackUser Feb 12 '16 at 16:49
  • @StackUser Yes. And, please, never use custom code for such tasks. It is very [hard to implement](http://stackoverflow.com/a/16226168/3405171). – v.ladynev Feb 12 '16 at 16:58

2 Answers2

2

Try this, bodyForm() is not adding your parameters and I could not found any kind of documentation.

public static void post(){
        try {
            StringBuilder http = new StringBuilder();
            http.append("https://maps.googleapis.com/maps/api/geocode/json");
            http.append("?");
            http.append("key=myAppKey");
            http.append("&");
            http.append("address=Sidney");
            Request maps = Request.Post(http.toString());
            System.out.println(maps.toString());
            Response mapsResponse = maps.execute();
            Content resp = mapsResponse.returnContent();
            String response = resp.toString();
            System.out.println(response);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Miguel Resendiz
  • 339
  • 3
  • 13
  • Your method seems to work and returns json correctly! Try also reply this, if you can: http://stackoverflow.com/questions/35345170/why-do-i-get-incomplete-answers-using-google-maps-api-in-java I have voted up your question and I'm planning to elege it as best one – StackUser Feb 12 '16 at 00:24
  • ` bodyForm()` adds parameters, but other way. Your answer has [some problems](http://stackoverflow.com/a/35366739/3405171), but anyway I up vote it. – v.ladynev Feb 12 '16 at 15:53
1

I did some investigations.

Looks like, It is impossible to use a POST request with parameters in the request body with Geocoding API (but it is need for Geolocation API, for an example). Geocoding API waits parameters in the URL. So for empty URL's parameters it returns an empty response.

Post requests have a very useful feature — an encoding of request parameters can be specified. With GET requests we have opposite situation — it is need to encode request's parameters. Only alphanumeric characters don't need to be encoded — refer Common pitfalls of URLs.

Based on this, @MiguelResendiz example will not always work. Consider the same, but simplified method — it is not need an API key for tests, and using Request.Post is the same as using Request.Get in this situation

private static void post(String address) throws Exception {
    StringBuilder http = new StringBuilder();
    http.append("https://maps.googleapis.com/maps/api/geocode/json");
    http.append("?");
    http.append("address=" + address);
    Content resp = Request.Post(http.toString()).execute().returnContent();
    System.out.println(resp);
}

It works for post("Sidney").

But when we do post("Red Light District") we have an exception, because of the address has spaces

java.lang.IllegalArgumentException: Illegal character in query at index 61

To do encoding we can use URIBuilder from Apache HTTP Client. And to perform a valid get request

String url = "https://maps.googleapis.com/maps/api/geocode/json";
String address = "Red Light District";
URIBuilder builder = new URIBuilder(url).setParameter("address", address);

Content response = Request.Get(builder.build()).execute().returnContent();

System.out.println(response);

It works pretty well.

v.ladynev
  • 19,275
  • 8
  • 46
  • 67
  • I have voted up your answer. I'll have to read with more attention the first part of it – StackUser Feb 12 '16 at 16:40
  • so, your URIBuilder encode the language character different from alphanumeric? – StackUser Feb 12 '16 at 16:48
  • Great, I have forgotten possible spaces and I had focus on the problem described. This solve better the problem – Miguel Resendiz Feb 12 '16 at 18:50
  • @MiguelResendiz But the main problem is still unsolved. This kind of a request returns only two results. – v.ladynev Feb 13 '16 at 01:07
  • @v.ladynev Google has some limitation when you have a free developer account. If you try to get this information without a key application you can get all the information if you use a free key application you are going to have a limit. https://developers.google.com/maps/documentation/geocoding/usage-limits?hl=es – Miguel Resendiz Feb 13 '16 at 03:26
  • @MiguelResendiz There is not such limit (only 2 addresses) by the link you provide . – v.ladynev Feb 13 '16 at 21:13
  • @v.ladynev Main problem still unsolved with your post method? Sure? I get 5 results, using my api query with your method, if I look for Sidney – StackUser Feb 13 '16 at 22:58
  • @StackUser May be I was wrong...Can't check it now :) – v.ladynev Feb 13 '16 at 23:00
  • @StackUser did you solve your problem? I did not have any other clue. – Miguel Resendiz Feb 26 '16 at 20:00