如何使用适用于java的google api客户端库向JSON数据发送POST请求?
问题描述:
我正在尝试使用google api客户端库发送发布请求,但无法成功。如何使用适用于java的google api客户端库向JSON数据发送POST请求?
这是我使用
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();
我没有得到预期的响应片段。我认为这是因为邮件参数,即电子邮件和密码没有以正确的格式发送。我需要发送给他们JSON。
注意:我没有使用谷歌网络服务库。
答
UrlEncodedContent用于发布HTTP表单内容(Content-Type:application/x-www-form-urlencoded)。如果内容类型是application/JSON你应该使用
答
我使用的是地图作为JSON的输入。该映射是为发布请求所使用的JsonHttpContent输入的。
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);