【问题标题】:Jersey rest client not adding query parameters泽西休息客户端不添加查询参数
【发布时间】:2015-01-01 15:19:40
【问题描述】:

我正在尝试为 google search api 制作一个简单的 jersey rest 客户端。

Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://www.googleapis.com/customsearch/v1");
target.queryParam("q", "mobile");
Response response = target.request().get();
System.out.println(response.readEntity(String.class));

正如您所注意到的,我没有包含 keycx。不用担心,这只是一个简单的演示。 访问urlhttps://www.googleapis.com/customsearch/v1?q=mobile时,响应为

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

这是正确的,因为我没有包含 keycx。当我执行上面的代码时,我得到的响应是

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: q",
    "locationType": "parameter",
    "location": "q"
   }
  ],
  "code": 400,
  "message": "Required parameter: q"
 }
}

这相当于访问没有任何参数的 url (https://www.googleapis.com/customsearch/v1),虽然我已经添加了这个 target.queryParam("q", "mobile");。我是不是做错了什么?

以上代码属于mavenized项目,依赖为

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.14</version>
</dependency>

【问题讨论】:

    标签: java rest jersey client google-search-api


    【解决方案1】:

    链接调用

    Response response= client.target("https://www.googleapis.com/customsearch/v1")
    .queryParam("q", "mobile").request().get();
    

    来自文档:

    返回:一个新的目标实例。

    注意:- 如果没有链接,则获取新创建的 webtarget 实例并使用它。

    WebTarget webTarget = client.target(snapshotGeneratorUrl);
    webTarget = webTarget.queryParam("foo","foo").queryParam("bar",bar);
    Response response = webTarget.request().get();
    

    【讨论】:

    • 我没有注意到它会创建一个新实例。我认为它只返回相同的实例,因此它可以用于链接。谢谢大佬。
    • @alkis 我也是这么想的。链接它也解决了我的问题。
    【解决方案2】:

    您可以改用 UriBuilder,并提供 uriBuilder 实例作为 client.target

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      相关资源
      最近更新 更多