How to send a POST request with JSON data using google api client library for java?

Harshal Kshatriya picture Harshal Kshatriya · Aug 3, 2012 · Viewed 8.3k times · Source

I'm trying to send a post request using the google api client library but not able to succeed.

This is the snippet I'm using

UrlEncodedContent urlEncodedContent = new UrlEncodedContent(paramMap);   //paramMap contains email and password keypairs
HttpRequest request = httpRequestFactory.buildPostRequest(new GenericUrl(Constants.PHP_SERVICE_BASE_PATH + mPath) , urlEncodedContent);
String response = request.execute().parseAsString();

I do not get the expected response. I think it is because the post parameters i.e email and password are not being sent in the correct format. I need to send them in JSON.

NOTE : I'm not using the library for a google web service.

Answer

userM1433372 picture userM1433372 · Jun 20, 2014

I'm using a Map as input of the JSON. The map is input for the JsonHttpContent used by the post request.

Map<String, String> json = new HashMap<String, String>();
json.put("lat", Double.toString(location.getLatitude()));
json.put("lng", Double.toString(location.getLongitude()));
final HttpContent content = new JsonHttpContent(new JacksonFactory(), json);
final HttpRequest request = getHttpRequestFactory().buildPostRequest(new GenericUrl(url), content);