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);
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?
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"
Use UriComponentsBuilder#build(boolean)
to indicate
whether all the components set in this builder are encoded (
true
) or not (false
)
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);
You can then use this URI
object as the first argument to the postForObject
method.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With