Jersey rest客户端不添加查询参数

Alk*_*ris 15 java rest client jersey google-search-api

我正在尝试为谷歌搜索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));
Run Code Online (Sandbox Code Playgroud)

你已经注意到我没有包括keycx.不用担心,这只是一个简单的演示.访问网址时https://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."
 }
}
Run Code Online (Sandbox Code Playgroud)

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

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Required parameter: q",
    "locationType": "parameter",
    "location": "q"
   }
  ],
  "code": 400,
  "message": "Required parameter: q"
 }
}
Run Code Online (Sandbox Code Playgroud)

这相当于访问没有任何参数(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>
Run Code Online (Sandbox Code Playgroud)

ari*_*xis 29

连锁电话

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

来自文档:

返回:新的目标实例.

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

WebTarget webTarget = client.target(snapshotGeneratorUrl);
webTarget = webTarget.queryParam("foo","foo").queryParam("bar",bar);
Response response = webTarget.request().get();
Run Code Online (Sandbox Code Playgroud)

  • 我没有注意到它将创建一个新实例。我以为它只返回相同的实例,因此可以用于链接。谢啦。 (2认同)
  • 这个答案需要更多的投票 (2认同)