java - RestTemplate 不转义 url

我正在像这样成功使用 Spring RestTemplate:

String url = "http://example.com/path/to/my/thing/{parameter}";
ResponseEntity<MyClass> response = restTemplate.postForEntity(url, payload, MyClass.class, parameter);

这很好。

但是,有时 parameter%2F。我知道这并不理想,但它就是这样。正确的 URL 应该是: http://example.com/path/to/my/thing/%2F 但是当我将 parameter 设置为 "%2F " 它被双重转义为 http://example.com/path/to/my/thing/%252F。如何防止这种情况发生?

最佳答案

不要使用 String URL,而是使用 UriComponentsBuilder 构建 URI

String url = "http://example.com/path/to/my/thing/";
String parameter = "%2F";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url).path(parameter);
UriComponents components = builder.build(true);
URI uri = components.toUri();
System.out.println(uri); // prints "http://example.com/path/to/my/thing/%2F"

使用 UriComponentsBuilder#build(boolean)表示

whether all the components set in this builder are encoded (true) or not (false)

这或多或少等同于替换 {parameter} 并自己创建一个 URI 对象。

String url = "http://example.com/path/to/my/thing/{parameter}";
url = url.replace("{parameter}", "%2F");
URI uri = new URI(url);
System.out.println(uri);

然后您可以将此 URI 对象用作 postForObject 方法的第一个参数。

https://stackoverflow.com/questions/28182836/

相关文章:

java - 是否可以在构造函数上使用@Resource?

java - Spring 的 JdbcTemplate 和事务

json - Spring REST 服务 : retrieving JSON from Reque

spring - 不使用 Maven 下载 Spring Jars

spring - 从 Spring boot 1.2 升级到 1.5.2 后,Tomcat 8.5

java - Spring 抛出 HttpMediaTypeNotAcceptableExcepti

java - Spring Boot 禁用/错误映射

spring - 无法 Autowiring ServletContext

spring - 如何在 Thymeleaf 和 Spring Boot 中显示消息?

java - Spring MVC 示例 Web 应用程序