Spring RestTemplate GET请求未给出正确的响应

时间:2019-06-19 15:05:18

标签: java spring-boot resttemplate

当我使用RestTemplate执行get请求时,服务器的响应与通过curl或在浏览器中获得的响应不同

我尝试使用URL编码并将URL记录到控制台以进一步解决问题,但无法解释差异。

UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(URL + "search/all")
                .queryParam("keywords", UriUtils.encode(person, StandardCharsets.UTF_8))
                .build(true);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(uriComponents.toUriString(), String.class);

RestTemplate生成的URL
https://example.com/api/v3/search/all?keywords=%C3%89tienne%20Racicot
返回响应: {}

表现: curl https://example.com/api/v3/search/all?keywords=%C3%89tienne%20Racicot
返回响应: {Person: {...} }

1 个答案:

答案 0 :(得分:0)

通过更改要调试的RestTemplate类的日志记录级别,我能够解决我的问题。将logging.level.org.springframework.web.client.RestTemplate=DEBUG添加到application.properties,您将获得RestTemplate执行的请求的详细日志。这帮助我注意到它正在编码第二次我不想传递的URL。为了避免这种情况,将uriComponents.toUri()传递给restTemplate.getForEntity(..)而不是字符串。