Java RestTemplate无法转义url

Java RestTemplate无法转义url,java,spring,resttemplate,Java,Spring,Resttemplate,我成功地使用了Spring RestTemplate,如下所示: stringurl=”http://example.com/path/to/my/thing/{参数}”; ResponseEntity response=restTemplate.postForEntity(url、有效负载、MyClass.class、参数); 这很好 但是,有时参数是%2F。我知道这并不理想,但事实就是如此。正确的URL应该是:http://example.com/path/to/my/thing/%2F但

我成功地使用了Spring RestTemplate,如下所示:

stringurl=”http://example.com/path/to/my/thing/{参数}”;
ResponseEntity response=restTemplate.postForEntity(url、有效负载、MyClass.class、参数);
这很好


但是,有时
参数
%2F
。我知道这并不理想,但事实就是如此。正确的URL应该是:
http://example.com/path/to/my/thing/%2F
但是当我将
参数设置为
“%2F”
时,它会被双重转义为
http://example.com/path/to/my/thing/%252F
。如何防止这种情况发生?

与其使用
字符串
URL,不如使用
UriComponentsBuilder构建
URI

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"
用来表示

此生成器中设置的所有组件是否已编码(
true
)(
false

这或多或少相当于替换
{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);

然后,您可以使用这个
URI
对象作为
postForObject
方法的第一个参数。

您可以告诉rest模板您已经对URI进行了编码。这可以使用UriComponentsBuilder.build(true)完成。这样rest模板将不会重新尝试转义uri。大多数rest模板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);
stringurl=”http://example.com/path/to/my/thing/{参数}”;
url=url.replace(“{parameter},“%2F”);
UriComponentsBuilder=UriComponentsBuilder.fromUrString(url);
//指示组件已转义
URI=builder.build(true.toUri();
ResponseEntity response=restTemplate.postForEntity(uri、有效负载、MyClass.class、参数);

谢谢。我解决这个问题的方式有点不同。在现实生活中,我的URL看起来更像
http://example.com/path/{param}/to/place
所以我做了
UriComponentsBuilder.fromHttpUrl(url.replace(“{param}”,parameter))
。我发现使用
UriComponentsBuilder.fromUristing()
比使用
fromHttpUrl()更好
因为它允许使用
/path/without/host
形式的URI,这在使用Spring
MockMvc
进行测试时非常有用。为什么这不是一个bug?它至少应该记录在Javadoc中。@GeorgeSofianos它记录在
restemplate
Javadoc中的注释中。假设模板参数需要编码。