泽西岛休息客户端未添加查询参数

2022-09-02 20:18:02

我正在尝试为谷歌搜索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));

正如你所注意到的,我没有包括和。别担心,这只是一个简单的演示。访问网址时,响应为keycxhttps://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/v1target.queryParam("q", "mobile");

上面的代码属于一个 mavenized 项目,依赖项是

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

答案 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();

答案 2

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