首页 > 解决方案 > 如何使用resttemplate对url进行编码,在查询参数中包含特殊字符

问题描述

使用 RestTemplate 在查询参数中包含特殊字符的 URL 时出现错误。

我的网址是这样的

 https://someendpoint?q=countryCode:(AB+yz)&q=type.code:12345&q=banner.code:A1&q=openDate[*+TO+NOW%2B3MONTH]%20&q=!date:[*+TO+NOW]

有人可以帮我如何使用 RestTemplate 对这种类型的 URL 进行编码。当我通过浏览器或邮递员点击时,此 URL 工作正常。

标签: spring-bootresttemplateurlencodespring-resttemplate

解决方案


您只需要添加 StringHttpMessageConverter。

  RestTemplate template = new RestTemplate();
  template.getMessageConverters()
    .add(0, new 
StringHttpMessageConverter(Charset.forName("UTF-8")));
 ResponseEntity<Object> response = template.exchange(endpoint, method, entity, 
                                                Object.class

推荐阅读