Search code examples
restjerseyjersey-client

Jersey client. MultivaluedMap goes empty


My RESTful client has this method:

public void testGetCateogrywiseData() {
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        client.addFilter(new LoggingFilter(System.out));
        WebResource service = client
                .resource("http://localhost:8080/MyApp/rest/publicdata");

        @SuppressWarnings("rawtypes")
        MultivaluedMap queryParams = new MultivaluedMapImpl();
        queryParams.add("latitude", "18.522387");
        queryParams.add("longitude", "73.878437");
        queryParams.add("categoryID", "2");

        service.queryParams(queryParams);

        ClientResponse response = service.get(ClientResponse.class);

        System.out.println(response.getStatus());
        System.out.println("Form response " + response.getEntity(String.class));
    }

On the server side the method looks like this:

@Path("publicdata")
@GET
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String getPublicData() throws JSONException {
    MultivaluedMap<String, String> valueMap = uriInfo.getQueryParameters();
    Long latString = Long.parseLong(valueMap.getFirst("latitude"));
    Long lonString = Long.parseLong(valueMap.getFirst("longitude"));
    Long categoryId = Long.parseLong(valueMap.getFirst("categoryID"));

    // Do necessary stuff and return json string
    return null;
}

My problem is the valueMap at the server end is always empty. It never gets the three parameters that I have sent from the client code. What am I missing?


Solution

  • The problem happens on this line:

    service.queryParams(queryParams);
    

    It successfully adds the query params, but it does not change the original service, it returns a new one to you. To make it work you need to change to this:

    service = service.queryParams(queryParams);