Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 635
Harshal Kshatriya Avatar asked Aug 03 '12 11:08

Harshal Kshatriya


2 Answers

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);
like image 130
userM1433372 Avatar answered Nov 03 '22 02:11

userM1433372


UrlEncodedContent is used for posting HTTP form content (Content-Type: application/x-www-form-urlencoded). If the Content-Type is application/json you should probably use

http://code.google.com/p/google-http-java-client/source/browse/google-http-client/src/main/java/com/google/api/client/http/json/JsonHttpContent.java

like image 26
Levente Kürti Avatar answered Nov 03 '22 02:11

Levente Kürti