17

I am using REST template to intentionally send a % in request uri, something like /items/a%b

String responseEntity = restTemplate.exchange("/items/a%b",
             requestObj.getHttpMethod(), requestEntity, String.class);

The restTemplate is converting the endoding of this uri and it is becoming /items/a%25b which makes sense as the rest template by default encodes the uri.

I tried using UriComponent for disabling the encoding of the uri

UriComponents uriComponents = UriComponentsBuilder.fromPath("/items/a%b").build();
URI uri= uriComponents.toUri();

String responseEntity = restTemplate.exchange(uri,
             requestObj.getHttpMethod(), requestEntity, String.class);

But this is not working as the uri again is of type URI which do the encoding. I am sure I am not using the UriComponents the right way.

I would really appreciate if anyone could point out what's the right way of disabling the encoding.

Thanks.

4
  • 1
    The request you say you want to send is illegal. Why do you believe that you need a dangling percent sign? Commented Dec 14, 2015 at 12:45
  • 1
    I am writing a test to make the server handling it gracefully. Its for a full integration tests hitting a remote server. so nothing is mocked. Commented Dec 14, 2015 at 12:52
  • 1
    The server shouldn't handle it "gracefully", it should return a 400 error. Commented Dec 14, 2015 at 18:28
  • 4
    That's what I need to test that the server returns 400, but the problem is that the restTemplate client is not able to send the request. I tried it using fiddler and the clients are able to send the request with % in the uri. Commented Dec 15, 2015 at 10:02

2 Answers 2

15

from the UriComponentsBuilder doc, exists method build(boolean encoded)

build(boolean encoded) Builds a UriComponents instance from the various components contained in this builder.

UriComponents uriComponents = UriComponentsBuilder.fromPath("/items/a%b").build(true);
Sign up to request clarification or add additional context in comments.

1 Comment

This is the best answer when you don't want to stop encoding on all RestTemplate usages.
12

I feel this is best way to disable encoding in RestTemplate which works fine for me

@Bean
public RestTemplate getRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory();
    defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
    restTemplate.setUriTemplateHandler(defaultUriBuilderFactory);
    return restTemplate;
}

1 Comment

It worked as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.