Jersey 休息客户端不添加查询参数

Jersey rest client not adding query parameters

我正在尝试为 google 搜索 api 制作一个简单的球衣休息客户端。

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>

链接调用

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

来自文档:

Returns:A new target instance.

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

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

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