【问题标题】:How to send a POST request with JSON data using google api client library for java?如何使用 Java 的 google api 客户端库发送带有 JSON 数据的 POST 请求?
【发布时间】:2025-12-06 08:15:01
【问题描述】:

我正在尝试使用 google api 客户端库发送发布请求,但无法成功。

这是我正在使用的 sn-p

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 发送它们。

注意:我没有将库用于谷歌网络服务。

【问题讨论】:

    标签: android json http-post httprequest google-api-java-client


    【解决方案1】:

    我使用 Map 作为 JSON 的输入。该映射是 post 请求使用的 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);
    

    【讨论】:

      【解决方案2】:

      UrlEncodedContent 用于发布 HTTP 表单内容(Content-Type:application/x-www-form-urlencoded)。如果 Content-Type 是 application/json 你应该使用

      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

      【讨论】: