Jersey client: How to add a list as query parameter
java, jersey, rest
Solution
`@GET` does support List of Strings
Setup: Java : 1.7 Jersey version : 1.9
Resource
@Path("/v1/test")
Subresource:
// receive List of Strings
@GET
@Path("/receiveListOfStrings")
public Response receiveListOfStrings(@QueryParam("list") final List<String> list){
log.info("receieved list of size="+list.size());
return Response.ok().build();
}
Jersey testcase
@Test
public void testReceiveListOfStrings() throws Exception {
WebResource webResource = resource();
ClientResponse responseMsg = webResource.path("/v1/test/receiveListOfStrings")
.queryParam("list", "one")
.queryParam("list", "two")
.queryParam("list", "three")
.get(ClientResponse.class);
Assert.assertEquals(200, responseMsg.getStatus());
}
Problem
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>() {}); ```