rest - 为什么 Jersey 的 UriBuilder.build 方法编码 #'s and %' s,而不是/?

标签 rest jersey urlencode jax-rs

我有一个相当典型的 REST API,除了资源的 id 不是整数,而是字符串,通常包含 /人物。因此,如果客户的 ID 是 string/with/slashes那么该客户的 URI 应该是 http://localhost/customers/string%2Fwith%2Fslashes .返回客户列表时,我想用 UriBuilder 构造该 URI。所以我可以把它放在 ATOM 样式链接元素的 href 中。但它并不完全有效;这是一个小测试类,显示了我的意思:

@Path("/customers")
public class JerseyTest {

  @Path("{id}")
  public Customer getCustomer(@PathParam("{id}") String id) {
    return null;
  }

  public static void main(String[] args) {
    buildURI("string#with#hashes"); // => http://localhost/customers/string%23with%23hashes
    buildURI("string/with/slashes"); // => http://localhost/customers/string/with/slashes
  }

  public static void buildURI(String id) {
    UriBuilder builder = UriBuilder.fromUri("http://localhost");
    builder.path(JerseyTest.class).path(JerseyTest.class, "getCustomer");
    URI uri = builder.build(id);
    System.out.println(uri);
  }
}
#像我期望的那样编码,但 /不要。我尝试使用 builder.build(URLEncoder.encode(id))相反,然后 UriBuilder 对 % 进行编码这样你就可以得到 .../string%252Fwith%252Fslashes !

它编码 ​​# 在我看来似乎不一致和 %但不是 / ,但我怀疑有一个我没有看到的充分理由。所以我的问题是:
  • 我怎样才能让 UriBuilder 给我 .../string%2Fwith%2Fslashes ,这是导致 Jersey 调用 getCustomer 的 URI与 id等于 string/with/slashes ? 编辑 :我发现了解决这个问题的方法:builder.buildFromEncoded(URLEncoder.encode(id)) .尽管如此,这个问题还是悬而未决,希望能得到第二部分的答案...
  • 更一般地说,为什么UriBuilder.build编码一些特殊字符,但不编码其他字符?

  • 我找到了 How do I encode URI parameter values? ,其中接受的答案是“使用 UriBuilder”。好吧,我正在使用它,但显然我使用不正确。

    最佳答案

    这似乎是一个已确认的问题:

    http://java.net/jira/browse/JAX_RS_SPEC-70

    您的解决方法听起来不错。

    关于rest - 为什么 Jersey 的 UriBuilder.build 方法编码 #'s and %' s,而不是/?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6287588/

    相关文章:

    java - bindFactory 不注入(inject)字段

    Eclipse 无法添加 apache tomcat 10

    jsonp - 在 Jersey Rest 中使用 @Consume 和 GET 请求

    .net - 转义 +(加号)在 URI

    ios - Swift 4 中 '(撇号) 的百分比编码输出不正确

    spring - 访问存储在 Redis 中的 Spring session 数据时出错

    web-services - 是否有可以测试 POST 方法的公共(public)网站?

    rest - 路由传入请求

    javascript - 用于回显相同 JSON 数据以进行测试的 REST API

    asp.net - HttpUtility.UrlEncode 和 Application_Start