如何传递包含斜杠字符的字符串路径参数?

时间:2016-07-18 11:00:41

标签: java spring jersey

我有这个REST资源:

@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 param可以包含斜杠字符:6576/M982,例如。

我用http://ip:port/samples/2000,2006,6576/M982调用它,但显然不起作用。

我还尝试使用http://ip:port/samples/2000,2006,6576%2FM982,将斜杠编码为%2F,但也没有工作,它也没有到达端点。

修改

我使用Retrofit来调用端点,我这样做:

@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,但仍无效。

3 个答案:

答案 0 :(得分:3)

,/等保留字符必须经过网址编码。

  • ,编码为%2C
  • /编码为%2F

尝试http://ip:port/samples/2000%2C2006%2C6576%2FM982

RFC 3986定义了可用作分隔符的以下reserved characters集。因此,它们需要URL编码:

: / ? # / [ ] / @ ! $ & ' ( ) * + , ; =

Unreserved characters不需要网址编码:

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编码,不适合您,您可以考虑使用查询参数。你的代码就像:

@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

请注意,/仍需要进行网址编码。

答案 1 :(得分:1)

尝试使用 {sample:。+} 代替 {sample}

@Path批注是一个正则表达式,而正则表达式与/字符不匹配。

要覆盖正则表达式,我们可以在".+的末尾添加PathParam

通过这种方式,我们可以在路径中允许/并避免使用%2F。

答案 2 :(得分:0)

实际上,.+ 有所帮助。只是它需要成为 @Path 而不是 @PathParam 的一部分。

示例:

@Path("{sample:.+}")