var responseEntity =
webClient
.get()
.uri(
uriBuilder ->
uriBuilder
.path("myendpoint")
.queryParam("email", email)
.build())
.retrieve()
这段代码的问题是,如果这里的电子邮件像my+email@gmail.com,URI默认编码不会在queryParam中编码+,如果我自己将字符串编码为Proper Uri encoded string: like: my%2Bemail@gmail.com,在这种情况下,这里的 URI 默认编码器也会对 % 符号进行编码。现在,如果我使用 uriBuilder 的 .encode() 函数,它也会在电子邮件中对 @ 进行编码。
我想实现这样的 URI:https://myendpoint?email=my%2Bemail@gmail.com
有人可以帮忙吗?非常感谢。
您可以这样实例化 URI:
URI.create("myendpoint?email=" + URLEncoder.encode("my+email@gmail.com", StandardCharsets.UTF_8).replace("%40", "@"))
虽然不是很优雅,但是很管用。
UriComponentsBuilder
的build(boolean
encoded
) 函数中的参数实际上定义了 URI 是否已经编码并防止再次对参数进行双重编码,因此我们可以将编码的电子邮件传递给参数并防止任何编码到通过 uriBuilder 本身在该电子邮件上运行。
var responseEntity =
webClient
.get()
.uri(
uriBuilder ->
UriComponentsBuilder.fromUri(uriBuilder.build())
.path("myendpoint")
.queryParam("email", getEncodedEmail(email))
.build(true)
.toUri())
.retrieve();
private String getEncodedEmail(String email){
return URLEncoder.encode(email, StandardCharsets.UTF_8).replace("%40","@");
}