RestTemplate to NOT escape url

huwr picture huwr · Jan 28, 2015 · Viewed 18.3k times · Source

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?

Answer

Sotirios Delimanolis picture Sotirios Delimanolis · Jan 28, 2015

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.