Jax-rs automatic decode pathparam

2020-06-09 07:53发布

问题:

I have a jax-rs service which receives a set of parameters in the path, pathparameters. These parameters may be strings containing values not suitable for urls, so they are urlencoded on the client side using the java.net.UrlEncoder like so:

String param = URLEncoder.encode(o.toString(), "UTF-8");

This is used to build the url supplier/group/param1/param2/param3. If one of these are changed due to the urlencoding, for instance if it is only a space, the string received on the service is a + sign.

@GET
@Path("{supplierId}/{groupCode}/{groupId}")
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public SupplierGroup getSupplierGroup(@PathParam("supplierId") BigDecimal supplierId,
        @PathParam("groupCode") String groupCode,
        @PathParam("groupId") BigDecimal groupId) {
    //now groupCode is "+", not " "
}

I would expect jaxrs to automatically decode encoded path params.

EDIT: Testing a bit more I discovered that when sending using %20 for the space, it is able to decode the param.

回答1:

The automatic encoding of pathparams works as expected. The problem was that %20is used to encode spaces in the url itself, while + is used to encode the query string(the part after the ?). Pathparams are really parts of the URL, so %20 should be used.

Using URI.toAsciiString() instead of UrlEncoder.encode(...) and passing the different parts gives a valid url that is decoded correctly.



回答2:

Quote from PathParam javadoc:

The value is URL decoded unless this is disabled using the Encoded annotation.