如何传递包含斜线字符的字符串路径参数? [英] How can I pass string path param containing slash character?
问题描述
我有这个REST资源:
I have this REST resource:
@GET
@Path("{business},{year},{sample}")
@Produces(MediaType.APPLICATION_JSON)
public Response getSample(
@PathParam("business") String business,
@PathParam("year") String year,
@PathParam("sample") String sampleId {
Sample sample = dao.findSample(business, year, sampleId);
return Response.ok(sample).build();
}
sample
参数可以包含斜杠字符:例如6576/M982
.
sample
param can contain slash character: 6576/M982
, for instance.
我正在用http://ip:port/samples/2000,2006,6576/M982
调用它,但是显然不能正常工作.
I'm calling it with http://ip:port/samples/2000,2006,6576/M982
but does not work, obviously.
我也尝试过使用http://ip:port/samples/2000,2006,6576%2FM982
,将斜杠编码为%2F
,但也不起作用,也无法到达端点.
I have also tried with http://ip:port/samples/2000,2006,6576%2FM982
, encoding the slash as %2F
, but doesn't work either, it doesn't reach the endpoint.
编辑
我正在使用Retrofit来调用端点,而我这样做:
I'm using Retrofit to call the endpoint and I do this:
@GET("/samples/{business},{year},{sampleId}")
Observable<Sample> getSampleById(
@Path("business") String business,
@Path("year") String year,
@Path(value = "sampleId", encoded = true) String sampleId);
使用encoded = true
,但仍然无法正常工作.
With encoded = true
, but still not working.
推荐答案
保留的字符(例如,
和/
)必须经过URL编码.
Reserved characters such as ,
and /
must be URL encoded.
-
,
编码为%2C
-
/
编码为%2F
,
is encoded as%2C
/
is encoded as%2F
尝试http://ip:port/samples/2000%2C2006%2C6576%2FM982
.
RFC 3986 定义了以下一组
The RFC 3986 defines the following set of reserved characters that can be used as delimiters. Hence, they require URL encoding:
: / ? # / [ ] / @ ! $ & ' ( ) * + , ; =
未保留的字符不需要URL编码:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
a b c d e f g h i j k l m n o p q r s t u v w x y z
0 1 2 3 4 5 6 7 8 9 - _ . ~
如果URL编码,
不是您的理想选择,则可以考虑使用查询参数.您的代码如下:
If URL encoding ,
is not a good alternative for you, you could consider using query parameters. Your code will be like:
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getSample(@QueryParam("business") String business,
@QueryParam("year") String year,
@QueryParam("sample") String sampleId {
...
}
您的网址将类似于http://ip:port/samples?business=2000&year=2006&sample=6576%2FM982
.
请注意,/
仍需要进行URL编码.
Please note that the /
still needs to be URL encoded.
这篇关于如何传递包含斜线字符的字符串路径参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!