How to disable encoding using RestTemplate

北战南征 提交于 2019-12-23 17:24:09

问题


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.


回答1:


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);



回答2:


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;
}


来源:https://stackoverflow.com/questions/34267371/how-to-disable-encoding-using-resttemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!