RestTemplate to NOT escape url
我正在成功使用Spring RestTemplate:
String url = "http://example.com/path/to/my/thing/{parameter}"; ResponseEntity response = restTemplate.postForEntity(url, payload, MyClass.class, parameter);
这很好。
但是,有时parameter
是%2F
。 我知道这不是理想的,但它就是它的本质。 正确的URL应该是: http://example.com/path/to/my/thing/%2F
: http://example.com/path/to/my/thing/%2F
但是当我将parameter
设置为"%2F"
它会被双重转义为http://example.com/path/to/my/thing/%252F
。 我该如何防止这种情况?
而不是使用String
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"
使用UriComponentsBuilder#build(boolean)
来表示
是否在此构建器中设置的所有组件都已编码(
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
方法的第一个参数。
您可以告诉其余模板您已经编码了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 response = restTemplate.postForEntity(uri, payload, MyClass.class, parameter);