如何使用 RestTemplate 禁用编码 [英] How to disable encoding using RestTemplate
问题描述
我正在使用 REST 模板故意在请求 uri 中发送一个 %,类似于 /items/a%b
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);
restTemplate
正在转换这个 uri 的结尾,它正在变成 /items/a%25b
这很有意义,因为默认情况下其余模板对 uri 进行编码.
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.
我尝试使用 UriComponent
来禁用 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);
但这不起作用,因为 uri 再次是进行编码的 URI 类型.我确定我没有以正确的方式使用 UriComponents.
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.
谢谢.
推荐答案
我觉得这是在 RestTemplate 中禁用编码的最佳方法,对我来说效果很好
@Bean
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
DefaultUriBuilderFactory defaultUriBuilderFactory = new DefaultUriBuilderFactory();
defaultUriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
restTemplate.setUriTemplateHandler(defaultUriBuilderFactory);
return restTemplate;
}
这篇关于如何使用 RestTemplate 禁用编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!