【问题标题】:Pass object as parameter in GET request using Google Http Client使用 Google Http 客户端在 GET 请求中将对象作为参数传递
【发布时间】:2012-11-09 03:23:55
【问题描述】:

我正在使用 Google Http Client 和 Jackson 将数据查询到后端 (JSON API)。

我需要传递参数(一个 Java bean 对象)。该对象可能有很少或很多场。最初我尝试将其作为内容传递如下:

HttpRequest request = requestFactory.buildGetRequest(getUrl(api)).setContent(new JsonCContent(jsonFactory, params));

但是,我不允许在 GET 操作中设置 HTTP 内容。

有什么建议可以传递这些参数吗?

在一种情况下: 我不想编写一个 util 方法来将此对象转换为 URL 参数字符串。但如果已经有可重用的 API 来做这件事,那就没问题了。

如果可能,我需要通用解决方案。因为我要将此应用于 600 个 JSON API 调用。

我的最后一个选择是将后端更改为期待 POST 请求而不是 GET,然后我在客户端执行 POST 操作。

谢谢

【问题讨论】:

    标签: json http httpclient jackson


    【解决方案1】:

    您可以使用 GenericUrl.put(继承自 GenericData)来设置查询参数,而不是扩展 GenericUrl。例如:

    GenericUrl genericUrl = new GenericUrl("http://yourapi.com/request");
    genericUrl.put("user", "user name");
    genericUrl.put("token", "token values");
    HttpRequest request = requestFactory.buildGetRequest(genericUrl);
    

    【讨论】:

      【解决方案2】:

      似乎预期的用途是扩展您用于 buildGetRequest() 调用的 URL 类。例如,假设您想提供两个额外的查询参数,称为“用户”和“令牌”。您可以通过以下方式做到这一点:

      HttpRequest request = requestFactory.buildGetRequest(
          new CustomUrl("http://www.yourserver.com").setUser(userId).setToken(token));
      

      CustomUrl 类定义为:

      public class CustomUrl extends GenericUrl {
          public CustomUrl(String encodedUrl) {
              super(encodedUrl);
          }
      
          @Key("user")
          private String mUserId;
      
          @Key("token")
          private String mToken;
      
          public CustomUrl setUser(String userId) {
              mUserId = userId;
              return this;
          }
      
          public CustomUrl setToken(String token) {
              mToken = token;
              return this;
          }
      }
      

      @Key 注释不需要这些值,但如果提供,这些值将用作相应查询参数的名称。如果省略,将使用变量名 (see example)

      查看google-http-client's javadoc了解更多信息。

      【讨论】:

      • 使用您建议的解决方案,对于我需要作为参数发送的每个 java bean,我必须为此创建一个自定义 URL 对象。好吧,那不是我想要的。还是谢谢
      猜你喜欢
      • 2014-12-21
      • 1970-01-01
      • 2021-05-31
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多