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;
}