我正在尝试为 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));
如您所见,我没有包含 key
和 cx
。别担心,这只是一个简单的演示。
当访问 url 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."
}
}
这是正确的,因为我没有包含 key
和 cx
。当我执行上面的代码时,我得到的响应是
{
"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", "移动");
.我做错了什么吗?
以上代码属于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();
关于java - Jersey 休息客户端不添加查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27731993/