我们正在从Java 8迁移到Java 11,因此从Spring Boot 1.5.6迁移到2.1.2。我们注意到,当使用RestTemplate时,“ +”号不再编码为“%2B”(由SPR-14828进行更改)。没关系,因为RFC3986并未将'+'列为保留字符,但在Spring Boot端点中接收到时仍被解释为''(空格)。
我们有一个搜索查询,可以将可选时间戳记作为查询参数。查询看起来像http://example.com/search?beforeTimestamp=2019-01-21T14:56:50%2B00:00
。
如果不进行双重编码,我们无法弄清楚如何发送已编码的加号。查询参数2019-01-21T14:56:50+00:00
将被解释为2019-01-21T14:56:50 00:00
。如果我们要自己编码参数(2019-01-21T14:56:50%2B00:00
),那么它将被接收并解释为2019-01-21T14:56:50%252B00:00
。
另一个限制是,我们在设置restTemplate时要在其他位置设置基本URL,而不是在执行查询的位置。
或者,是否有一种方法可以强制端点不将“ +”解释为“”?
我写了一个简短的示例,演示了一些实现更严格编码的方法,其缺点已解释为注释:
package com.example.clientandserver;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@SpringBootApplication
@RestController
public class ClientAndServerApp implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(ClientAndServerApp.class, args);
}
@Override
public void run(String... args) {
String beforeTimestamp = "2019-01-21T14:56:50+00:00";
// Previously - base url and raw params (encoded automatically). This worked in the earlier version of Spring Boot
{
RestTemplate restTemplate = new RestTemplateBuilder().rootUri("http://localhost:8080").build();
UriComponentsBuilder b = UriComponentsBuilder.fromPath("/search");
if (beforeTimestamp != null) {
b.queryParam("beforeTimestamp", beforeTimestamp);
}
restTemplate.getForEntity(b.toUriString(), Object.class);
// Received: 2019-01-21T14:56:50 00:00
// Plus sign missing here ^
}
// Option 1 - no base url and encoding the param ourselves.
{
RestTemplate restTemplate = new RestTemplate();
UriComponentsBuilder b = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/search");
if (beforeTimestamp != null) {
b.queryParam("beforeTimestamp", UriUtils.encode(beforeTimestamp, StandardCharsets.UTF_8));
}
restTemplate.getForEntity(b.build(true).toUri(), Object.class).getBody();
// Received: 2019-01-21T14:56:50+00:00
}
// Option 2 - with base url, but templated, so query parameter is not optional.
{
RestTemplate restTemplate = new RestTemplateBuilder().rootUri("http://localhost:8080").uriTemplateHandler(new DefaultUriBuilderFactory()).build();
Map<String, String> params = new HashMap<>();
params.put("beforeTimestamp", beforeTimestamp);
restTemplate.getForEntity("/search?beforeTimestamp={beforeTimestamp}", Object.class, params);
// Received: 2019-01-21T14:56:50+00:00
}
}
@GetMapping("/search")
public void search(@RequestParam String beforeTimestamp) {
System.out.println("Received: " + beforeTimestamp);
}
}
答案 0 :(得分:5)
我们意识到在完成编码后,可以在拦截器中修改URL。因此,一种解决方案是使用拦截器,该拦截器对查询参数中的加号进行编码。
RestTemplate restTemplate = new RestTemplateBuilder()
.rootUri("http://localhost:8080")
.interceptors(new PlusEncoderInterceptor())
.build();
一个简短的例子:
public class PlusEncoderInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
return execution.execute(new HttpRequestWrapper(request) {
@Override
public URI getURI() {
URI u = super.getURI();
String strictlyEscapedQuery = StringUtils.replace(u.getRawQuery(), "+", "%2B");
return UriComponentsBuilder.fromUri(u)
.replaceQuery(strictlyEscapedQuery)
.build(true).toUri();
}
}, body);
}
}
答案 1 :(得分:1)
为了解决这类问题,我发现手动构建 URI 更容易。
URI uri = new URI(siteProperties.getBaseUrl()
+ "v3/elements/"
+ URLEncoder.encode("user/" + user + "/type/" + type, UTF_8)
+ "/"
+ URLEncoder.encode(id, UTF_8)
);
restTemplate.exchange(uri, DELETE, new HttpEntity<>(httpHeaders), Void.class);
答案 2 :(得分:0)
这里也讨论了这个问题。
Encoding of URI Variables on RestTemplate [SPR-16202]
一个更简单的解决方案是将URI构建器上的编码模式设置为VALUES_ONLY。
DefaultUriBuilderFactory builderFactory = new DefaultUriBuilderFactory();
builderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
RestTemplate restTemplate = new RestTemplateBuilder()
.rootUri("http://localhost:8080")
.uriTemplateHandler(builderFactory)
.build();
与使用查询参数时使用PlusEncodingInterceptor的结果相同。