I'm creating a Jersey client for a GET service that has a List as query parameter. According to the documentation, it's possible to have a List as a query parameter (this information is also at @QueryParam javadoc), check it out:
In general the Java type of the method parameter may:
- Be a primitive type;
- Have a constructor that accepts a single String argument;
- Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String) and java.util.UUID.fromString(String)); or
- Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.
Sometimes parameters may contain more than one value for the same name. If this is the case then types in 4) may be used to obtain all values.
However, I can't figure out how to add a List query parameter using Jersey client.
I understand alternative solutions are:
- Use POST instead of GET;
- Transform the List into a JSON string and pass it to the service.
The first one is not good, because the proper HTTP verb for the service is GET. It is a data retrieval operation.
The second will be my option if you can't help me out. :)
I'm also developing the service, so I may change it as needed.
Thanks!
Update
Client code (using json)
Client client = Client.create();
WebResource webResource = client.resource(uri.toString());
SearchWrapper sw = new SearchWrapper(termo, pagina, ordenacao, hits, SEARCH_VIEW, navegadores);
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("user", user.toUpperCase());
params.add("searchWrapperAsJSON", (new Gson()).toJson(sw));
ClientResponse clientResponse = webResource .path("/listar")
.queryParams(params)
.header(HttpHeaders.AUTHORIZATION, AuthenticationHelper.getBasicAuthHeader())
.get(ClientResponse.class);
SearchResultWrapper busca = clientResponse.getEntity(new GenericType<SearchResultWrapper>() {});
@GET
does support List of StringsSetup:
Java : 1.7
Jersey version : 1.9
Resource
Subresource:
Jersey testcase
GET Request with JSON Query Param
Post Request :
i agree with you about alternative solutions which you mentioned above
and its true that you can't add
List
toMultiValuedMap
because of its impl classMultivaluedMapImpl
have capability to accept String Key and String Value. which is shown in following figurestill you want to do that things than try following code.
Controller Class
Cleint Class
hope this'll help you.
If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:
Your client would send a request corresponding to:
Which would result in
inputList
being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'