Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Springboot : Prevent double encoding of % by Resttemplate

Our code uses Asyncresttemplate as follows

String uri = http://api.host.com/version/test?address=%23&language=en-US&format=json

getAysncRestTemplate().getForEntity(uri, String.class);

But %23 is double encoded in Rest template as %2523 and the url becomes http://api.host.com/version/test?address=%2523&language=en-US&format=json, But I need to pass encoded string, It doesn't encode if I pass decoded data '#'

How can I send this request without double encoding the URL?

Already tried using UriComponentsBuilder Avoid Double Encoding of URL query param with Spring's RestTemplate

like image 558
Abhi Avatar asked Oct 18 '25 15:10

Abhi


2 Answers

The uri argument (of type String) passed to the RestTemplate is actually a URI template as per the JavaDoc. The way to use the rest template without the double encoding would be as follows:

getAysncRestTemplate().getForEntity(
        "http://api.host.com/version/test?address={address}&language=en-US&format=json", 
        String.class, 
        "#"); // (%23 decoded)

If you know you already have a properly encoded URL you can use the method that has a URI as the first parameter instead:

restTemplate.getForEntity(
        new URI("http://api.host.com/version/test?address=%23&language=en-US&format=json"),
        String.class);
like image 176
Auke Avatar answered Oct 21 '25 04:10

Auke


You can avoid this by not encoding any part of it yourself, e.g use # rather than %23

like image 27
AleksW Avatar answered Oct 21 '25 03:10

AleksW