4

I'm using the jersey client to send a query param to my jersey server. This is the query: ?sort=id+ASC

But in my code that retrieves this query param, return uriInfo.getQueryParameters().getFirst("sort");, this value evaluates to id ASC. Why is this happening and how can I prevent it?

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • 3
    A query string of `?sort=id+ASC` _does_ represent a parameter value of "id ASC" because query strings are `application/x-www-form-urlencoded`. If you want to send a parameter value of "id+ASC" then you'd have to use a query string of `?sort=id%2BASC` – Ian Roberts Feb 06 '14 at 21:38
  • @IanRoberts I see. I guess I can just live with it. – Daniel Kaplan Feb 06 '14 at 21:42

1 Answers1

8

Apart from @IanRoberts's suggestion, you could make use of the @Encoded annotation to get to the original undecoded value of you parameter (by default Jersey decodes the values and that's why id+ASC becomes id ASC in your code).

The following example retrieves the decoded value as for the default behavior:

@GET
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response test(@QueryParam("sort") String sort) {
    // sort is "id ASC"
    return Response.ok().entity(sort).build();
}

To change the behavior you just add @Encoded:

@GET
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response test(@QueryParam("sort") @Encoded String sort) {
    // sort is "id+ASC"
    return Response.ok().entity(sort).build();
}
Bogdan
  • 23,890
  • 3
  • 69
  • 61
  • 1
    @tieTYT: Yes. I've done a quick search to see in what version it was added and it seems it's there since 1.4: https://jersey.java.net/apidocs/1.4/jersey/javax/ws/rs/Encoded.html – Bogdan Mar 01 '14 at 21:20