gpt4 book ai didi

java - 使用 UriComponentsBuilder 编码查询参数

转载 作者:搜寻专家 更新时间:2023-11-01 01:49:23 25 4
gpt4 key购买 nike

我很难理解 UriComponentsBuilder 的行为.我想用它对查询参数中的 URL 进行编码,但它似乎只转义 % 字符,而不转义其他必要的字符,例如 &

查询参数中根本未编码的 URL 示例:

UriComponentsBuilder.fromUri("http://example.com/endpoint")
.queryParam("query", "/path?foo=foo&bar=bar")
.build();

输出:http://example.com/endpoint?query=/path?foo=foo&bar=bar

这是不正确的,因为未编码的 & 导致 bar=bar 被解释为 /endpoint 的查询参数而不是 /路径

但是,如果我使用包含 % 字符的输入::

UriComponentsBuilder.fromUri("http://example.com/endpoint")
.queryParam("query", "/path?foo=%20bar")
.build();

输出:http://example.com/endpoint?query=/path?foo=%2520bar

% 字符被转义。

似乎不一致的是 UriComponentsBuilder 会自动转义 % 字符而不是其他保留字符。

使用 UriComponentsBuilder 将 URL 编码为查询参数的正确过程是什么?

最佳答案

在您的示例中,构建 UriComponents 对象未编码或规范化。确保应用编码:

  1. 通过调用 encode() 自行编码方法(另见 normalize() 方法):

    UriComponents u = UriComponentsBuilder.fromHttpUrl("http://example.com/endpoint")
    .queryParam("query", "/path?foo=foo&bar=bar")
    .build()
    .encode();
    // http://example.com/endpoint?query=/path?foo%3Dfoo%26bar%3Dbar
  2. 如果用于构造UriComponents 的参数已经编码,则使用build(true) 方法

    UriComponents u = UriComponentsBuilder.fromHttpUrl("http://example.com/endpoint")
    .queryParam("query", "/path?foo=foo&bar=bar")
    .build(true);
    // IllegalArgumentException: Invalid character '=' for QUERY_PARAM in "/path?foo=foo&bar=bar"

在引擎盖下 HierarchicalUriComponents.encode(String) 方法执行实际的编码。几次内部调用后,它调用 HierarchicalUriComponents.encodeBytes(byte[], HierarchicalUriComponents.Type),其中 HierarchicalUriComponents.Type 枚举控制 URL 的哪一部分允许使用哪些字符。此检查基于 RFC 3986 .简而言之,Spring 对 URL 的每一部分都有自己的编码逻辑。

关于java - 使用 UriComponentsBuilder 编码查询参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47217647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com