java - RestTemplate 不转义 url

标签 java spring resttemplate

我正在像这样成功使用 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 方法的第一个参数。

关于java - RestTemplate 不转义 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28182836/

相关文章:

java - 在 Spring 中消耗大量 json 有效负载的最佳方法?

java - 使 REST 客户端调用更快的技巧

java - 使用正则表达式匹配字符串中的数字

spring - 使用 Spring-boot 配置的 Logstash/Logback 设置

java - 读取输入消息时出现 I/O 错误;嵌套异常是 java.io.IOException : Stream closed

java - 在 java .spring 中创建一个临时数据持有者。 hibernate

spring - 在 Spring RestTemplate 中设置 Authorization header

java - jSTL 标签 <c :forEach is not working

Java 线程异常终止并出现消息为 null 的异常。

JavaFX:如何监听非 UI 对象上的事件