Search code examples
javaspring-bootresttemplate

How can i use % with RestTemplate


I am trying to make a HTTP request to a API with a route like this:

https://example.test/{ID}/get

The problem is, the ID starts with %, something like "%123123123", after the "excute" method, locate in RestTemplate class, this ID's becomes %25123123123, % changes into %25. More specific, in this line of the method:

URI expanded = getUriTemplateHandler().expand(url, uriVariables);

Here my uriVariables is just a empty Object, and when i manually change the value of expanded variable removing "25", the request works just fine.

Anyone knows how to fix it ?


Solution

  • After Spring 5, the DefaultUriBuilderFactory, used by RestTemplate, defaults is EncodingMode.URI_COMPONENT, as described below:

    Expand URI variables first, and then encode the resulting URI component values, replacing only non-ASCII and illegal (within a given URI component type) characters, but not characters with reserved meaning.

    If you want your URI to be unencoded like I do, just create a new DefaultUriBuilderFactory with EncodingMode.NONE and add it to your RestTemplate:

    DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory();
    uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setUriTemplateHandler(uriBuilderFactory);
    

    You can check here for other EncondingModes.