问题描述
我有一个jax-rs服务,该服务在path中接收一组参数pathparameters.这些参数可能是包含不适合url的值的字符串,因此它们使用java.net.UrlEncoder在客户端进行urlencode编码,如下所示:
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");
这用于构建URL supplier/group/param1/param2/param3
.如果由于urlencoding而更改了其中之一,例如,如果仅是空格,则在服务上接收到的字符串为+
符号.
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 " "
}
我希望jaxrs能够自动解码编码的路径参数.
I would expect jaxrs to automatically decode encoded path params.
经过更多测试,我发现使用%20
进行发送时,它可以对参数进行解码.
Testing a bit more I discovered that when sending using %20
for the space, it is able to decode the param.
推荐答案
pathparams的自动编码按预期工作.问题是%20
用于对url本身中的空格进行编码,而+
用于对查询字符串(?之后的部分)进行编码.路径参数实际上是URL的一部分,因此应使用%20.
The automatic encoding of pathparams works as expected. The problem was that %20
is 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.
使用URI.toAsciiString()
代替UrlEncoder.encode(...)
并传递不同的部分,可以得到有效的网址,并且可以正确解码.
Using URI.toAsciiString()
instead of UrlEncoder.encode(...)
and passing the different parts gives a valid url that is decoded correctly.
这篇关于Jax-rs自动解码pathparam的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!