Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RestTemplate to NOT escape url

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?

like image 369
huwr Avatar asked Jan 28 '15 00:01

huwr


2 Answers

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.

like image 51
Sotirios Delimanolis Avatar answered Nov 15 '22 10:11

Sotirios Delimanolis


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);
like image 44
rouble Avatar answered Nov 15 '22 08:11

rouble