简体   繁体   English

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

[英]Spring RestTemplate GET request does not give correct response

When I perform a get request with RestTemplate, the server's response is not the same as what I get via a curl or in my browser 当我使用RestTemplate执行get请求时,服务器的响应与通过curl或浏览器获得的响应不同

I've tried playing with the URL encoding and logging the url to the console to further troubleshoot but can't explain the discrepancy. 我尝试使用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);

The resultant URL from RestTemplate: 来自RestTemplate的结果URL
https://example.com/api/v3/search/all?keywords=%C3%89tienne%20Racicot
returns the response: {} 返回响应: {}

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

I was able to resolve my issue by changing the logging level for the RestTemplate class to debug. 我能够通过将RestTemplate类的日志记录级别更改为调试来解决我的问题。 Add logging.level.org.springframework.web.client.RestTemplate=DEBUG to application.properties and you'll get a detailed log of the requests RestTemplate performs. logging.level.org.springframework.web.client.RestTemplate=DEBUG添加到application.properties ,您将获得RestTemplate执行的请求的详细日志。 This helped me notice that it was encoding the url I was passing a second time which I do not want. 这有助于我注意到它正在编码我第二次通过的网址,这是我不想要的。 To avoid this pass uriComponents.toUri() to restTemplate.getForEntity(..) instead of a string. 为了避免这种情况, uriComponents.toUri()传递给restTemplate.getForEntity(..)而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM