gpt4 book ai didi

java - 避免使用 Spring 的 RestTemplate 对 URL 查询参数进行双重编码

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:43:09 24 4
gpt4 key购买 nike

<分区>

我正在尝试使用 Spring 的 RestTemplate::getForObject 来请求具有 URL 查询参数的 URL。

我试过:

  • 使用字符串
  • 使用 URI::new 创建 URI
  • 使用 URI::create 创建 URI
  • 使用 UriComponentsBuilder 构建 URI

无论我使用其中的哪一个,使用 URLEncoder::encode 对 url 查询参数进行编码都会得到双重编码,并且使用此编码会使 url 查询参数保持未编码状态。

如何在不对 URL 进行双重编码的情况下发送此请求?方法如下:

try {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(detectUrl)
.queryParam("url", URLEncoder.encode(url, "UTF-8"))
.queryParam("api_key", "KEY")
.queryParam("api_secret", "SECRET");
URI uri = builder.build().toUri();
JSONObject jsonObject = restTemplate.getForObject(uri, JSONObject.class);
return jsonObject.getJSONArray("face").length() > 0;
} catch (JSONException | UnsupportedEncodingException e) {
e.printStackTrace();
}

这是一个例子:

没有 URLEncoder:

http://www.example.com/query?url=http://query.param/example&api_key=KEY&api_secret=SECRET

使用 URLEncoder:

http://www.example.com/query?url=http%253A%252F%252Fquery.param%252Fexample&api_key=KEY&api_secret=SECRET

“:”应编码为 %3A,“/”应编码为 %2F。这确实发生了 - 但随后 % 被编码为 %25。

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