我希望我的REST客户端使用Spring Web的RestTemplate,对URL参数中的所有特殊字符(不仅是非法字符)进行%编码。的Spring Web的文档指出,编码方法可以通过配置来改变DefaultUriBuilderFactory使用RestTemplate带setEncodingMode(EncodingMode.VALUES_ONLY):
String baseUrl = "http://example.com";
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl)
factory.setEncodingMode(EncodingMode.VALUES_ONLY);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(factory);
这应该“将UriUtils.encode(String,Charset)应用于每个URI变量值”,这反过来将“对RFC 3986中定义的URI中任何非法或具有保留含义的所有字符进行编码”。
我编写了以下测试用例,以尝试证明更改为EncodingMode.VALUES_ONLY不会产生预期的效果。(具有相关性执行它org.springframework.boot:spring-boot-starter:2.0.3.RELEASE,org.springframework:spring-web:5.0.7.RELEASE,org.springframework.boot:spring-boot-starter-test:2.0.3.RELEASE)
package com.example.demo.encoding;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import java.nio.charset.StandardCharsets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.client.RestClientTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.DefaultUriBuilderFactory;
此测试失败java.lang.AssertionError: Request URI expected:<https://host?parameter=%2B%3A%2F> but was:<https://host?parameter=+:/>。那我在做什么错?是Spring Framework中的错误,还是MockRestServiceServer在验证期望值之前对URL进行了解码?
相关分类