java RestTemplate 不转义 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28182836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RestTemplate to NOT escape url
提问by huwr
I'm using Spring RestTemplate successfully like this:
我正在像这样成功地使用 Spring RestTemplate:
String url = "http://example.com/path/to/my/thing/{parameter}";
ResponseEntity<MyClass> response = restTemplate.postForEntity(url, payload, MyClass.class, parameter);
And that is good.
这很好。
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?
但是,有时parameter
是%2F
。我知道这并不理想,但它就是这样。正确的 URL 应该是:http://example.com/path/to/my/thing/%2F
但是当我设置parameter
为"%2F"
它时,它会被双重转义为http://example.com/path/to/my/thing/%252F
. 我如何防止这种情况?
回答by Sotirios Delimanolis
Instead of using a String
URL, build a URI
with a UriComponentsBuilder
.
如果不使用的String
URL,建立一个URI
具有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"
Use UriComponentsBuilder#build(boolean)
to indicate
使用UriComponentsBuilder#build(boolean)
指示
whether all the components set in this builder are encoded (
true
)or not (false
)
此构建器中设置的所有组件是否已编码 (
true
)或未编码(false
)
This is more or less equivalent to replacing {parameter}
and creating a URI
object yourself.
这或多或少相当于自己替换{parameter}
和创建URI
对象。
String url = "http://example.com/path/to/my/thing/{parameter}";
url = url.replace("{parameter}", "%2F");
URI uri = new URI(url);
System.out.println(uri);
You can then use this URI
object as the first argument to the postForObject
method.
然后,您可以将此URI
对象用作该postForObject
方法的第一个参数。
回答by rouble
You can tell the rest template that you have already encoded the uri. This can be done using UriComponentsBuilder.build(true). This way rest template will not reattempt to escape the uri. Most of the rest template api's will accept a URI as the first argument.
您可以告诉其余模板您已经对 uri 进行了编码。这可以使用 UriComponentsBuilder.build(true) 来完成。这样,rest 模板将不会重新尝试转义 uri。大多数其他模板 api 将接受 URI 作为第一个参数。
String url = "http://example.com/path/to/my/thing/{parameter}";
url = url.replace("{parameter}", "%2F");
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url);
// Indicate that the components are already escaped
URI uri = builder.build(true).toUri();
ResponseEntity<MyClass> response = restTemplate.postForEntity(uri, payload, MyClass.class, parameter);