4

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

Abhi
  • 319
  • 1
  • 5
  • 19
  • Follow this link: https://stackoverflow.com/a/6138183/7871971 – SamratV Apr 12 '19 at 15:08
  • Why do you need to send `%23` in as part of this call? A query which takes a `#` as part of it is *very* unusual. – Makoto Apr 12 '19 at 15:08
  • Facing issue for this api as well http://api.host.com/version/test?address=AA%2FAA&language=en-US&format=json is converted to http://api.host.com/version/test?address=AA%252FAA&language=en-US&format=json as well – Abhi Apr 12 '19 at 15:14
  • It appears that your api encodes the url. So you need to pass unencoded url and the api will encode it for itself. – SamratV Apr 12 '19 at 15:14
  • URL encoded value of '#' is %23 In the case of http://api.host.com/version/test?address=%23&language=en-US&format=json, it decodes to http://api.host.com/version/test?address=%2523&language=en-US&format=json But not in the case of http://api.host.com/version/test?address=#&language=en-US&format=json – Abhi Apr 12 '19 at 15:31
  • 1
    Refer to this; https://stackoverflow.com/questions/8297215/spring-resttemplate-get-with-parameters You need to fully use the framework - not to hack it. Also, you can try getForEntity(String url, Class responseType, Map uriVariables), which allows you to put uriVariables as a Map. – Edward Aung Apr 16 '19 at 06:02
  • The issue was due to this , thus solved -https://stackoverflow.com/questions/28182836/resttemplate-to-not-escape-url – Abhi Apr 16 '19 at 14:02

2 Answers2

9

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);
Auke
  • 534
  • 5
  • 16
1

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

AleksW
  • 703
  • 3
  • 12