18

I'm trying to make a simple jersey rest client for google search 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));

As you've noticed I haven't included key and cx. Don't worry about that, it's just a simple demo. When visiting the url https://www.googleapis.com/customsearch/v1?q=mobile, the response is

{
 "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."
 }
}

Which is correct since I haven't included key and cx. When I execute the code above, the response I'm getting is

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

Which is equivalent of visiting the url without any parameters (https://www.googleapis.com/customsearch/v1), although I've added this target.queryParam("q", "mobile");. Am I doing something wrong?

The code above belongs to a mavenized project and the dependency is

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.14</version>
</dependency>
Alkis Kalogeris
  • 17,044
  • 15
  • 59
  • 113

2 Answers2

34

chain the call

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

from the docs:

Returns:A new target instance.

Note :- If not chaining then get newly created webtarget instance and use it.

WebTarget webTarget = client.target(snapshotGeneratorUrl);
webTarget = webTarget.queryParam("foo","foo").queryParam("bar",bar);
Response response = webTarget.request().get();
Amit
  • 30,756
  • 6
  • 57
  • 88
arisalexis
  • 2,079
  • 2
  • 21
  • 42
  • 2
    I didn't notice that it will create a new instance. I thought it returns the same instance only so it can be used for chaining. Thanks man. – Alkis Kalogeris Jan 01 '15 at 15:32
  • @alkis I thought the same. Chaining it fixed my problem too. – Aebsubis Mar 13 '17 at 11:01
  • 1
    @Aebsubis me too, I thought queryParam() is a setter, doesn't notice it is return new instance, thanks STS doesn't return any error on design time or runtime, so I spent 2 days on it. – Cheung May 03 '22 at 02:58
2

You can use UriBuilder instead, and provide the uriBuilder instance as the client.target