RestTemplate不能转义URL [英] RestTemplate to NOT escape url
问题描述
我正在像这样成功地使用Spring RestTemplate:
I'm using Spring RestTemplate successfully like this:
String url = "http://example.com/path/to/my/thing/{parameter}";
ResponseEntity<MyClass> response = restTemplate.postForEntity(url, payload, MyClass.class, parameter);
那很好.
但是,有时parameter
是%2F
.我知道这并不理想,但事实就是如此.正确的URL应该是:http://example.com/path/to/my/thing/%2F
,但是当我将parameter
设置为"%2F"
时,它会两次转义到http://example.com/path/to/my/thing/%252F
.我该如何预防?
However, sometimes parameter
is %2F
. I know this isn't ideal, but it is what it is. The correct URL should be: http://example.com/path/to/my/thing/%2F
but when I set parameter
to "%2F"
it gets double escaped to http://example.com/path/to/my/thing/%252F
. How do I prevent this?
推荐答案
而不是使用String
URL,而是使用UriComponentsBuilder
构建URI
.
Instead of using a String
URL, build a URI
with a UriComponentsBuilder
.
String url = "http://example.com/path/to/my/thing/";
String parameter = "%2F";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).path(parameter);
UriComponents components = builder.build(true);
URI uri = components.toUri();
System.out.println(uri); // prints "http://example.com/path/to/my/thing/%2F"
使用 UriComponentsBuilder#build(boolean)
表示
此构建器中设置的所有组件是否均已编码(
true
)(false
)
这或多或少等同于替换{parameter}
并自己创建URI
对象.
This is more or less equivalent to replacing {parameter}
and creating a URI
object yourself.
String url = "http://example.com/path/to/my/thing/{parameter}";
url = url.replace("{parameter}", "%2F");
URI uri = new URI(url);
System.out.println(uri);
然后可以将此URI
对象用作postForObject
方法的第一个参数.
You can then use this URI
object as the first argument to the postForObject
method.
这篇关于RestTemplate不能转义URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!