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

时间:2015-01-01 15:19:41

标签: java rest jersey client 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));

正如您已经注意到我没有包含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."
 }
}

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

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

相当于访问没有任何参数的网址(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>

2 个答案:

答案 0 :(得分:27)

链接电话

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

答案 1 :(得分:1)

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