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

Héc*_*tor 2 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();
}
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

使用encoded = true,但仍然无法正常工作。

cas*_*lin 5

保留字符(例如,和)/必须经过URL编码。

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

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


RFC 3986个定义了以下一组保留的字符可被用作分隔符。因此,它们需要URL编码:

: / ? # / [ ] / @ ! $ & ' ( ) * + , ; =
Run Code Online (Sandbox Code Playgroud)

未保留的字符不需要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 - _ . ~
Run Code Online (Sandbox Code Playgroud)

如果URL编码,不是您的理想选择,则可以考虑使用查询参数。您的代码将类似于:

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getSample(@QueryParam("business") String business, 
                          @QueryParam("year") String year,
                          @QueryParam("sample") String sampleId {
    ...
}
Run Code Online (Sandbox Code Playgroud)

您的网址将是http://ip:port/samples?business=2000&year=2006&sample=6576%2FM982

请注意,/仍然需要对URL进行编码。

  • @Amalgovinus 是的。但是,在 OP 情况下,看起来 `/` 不是路径分隔符。所以编码没问题。 (2认同)