遇到一个RestTemplate请求中带特殊字符的问题。
RestTemplate 进行数据请求如果url中带有特殊字符时会导致请求出错,这边遇到的‘#’的问题,接受到的传参会省略‘#’后面的内容;还有其他一些特殊符号如 +、=、&、%等。
HttpHeaders headers = new HttpHeaders();
headers.add("timestamp", System.currentTimeMillis() + "");
String url = "http://localhost:8761/order/search?goodsName=AL033#测试";
HttpEntity<?> entity = new HttpEntity<>(headers);
HttpEntity<String> response = restTemplate.exchange(url,HttpMethod.GET,entity,String.class);
restTemplate的exchange方法,参数url是String类型在发送请求之前会先将String类型的url转为URI类型的url,如下面的restTemplate的源码中的方法:
public <T> T execute(String url, HttpMethod method, @Nullable RequestCallback requestCallback,
@Nullable ResponseExtractor<T> responseExtractor, Object... uriVariables) throws RestClientException {
URI expanded = getUriTemplateHandler().expand(url, uriVariables);
return doExecute(expanded, method, requestCallback, responseExtractor);
}
因此这里直接采用restTemplate传参为URI的方法,将url的字符串编码转成URI就可以了:
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.build().encode().toUri();
HttpEntity<String> response = restTemplate.exchange(uri,HttpMethod.GET,entity,String.class);