Spring MVC 使用Sping Boot RestTemplate时在响应头中接收到不正确的内容类型

j9per5c4  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(74)

在提供的代码片段中,我使用Sping Boot 的RestTemplate发出HTTP GET请求。目的是基于从URL接收的响应的Content-Type执行特定的业务逻辑。然而,对于URL https://worldtimeapi.org/api/timezone/Europe/London,我遇到了从响应中检索的Content-Type值与使用Postman或curl等工具执行相同请求时观察到的值之间的差异。
下面是我用来发出请求的代码:

String url = "https://worldtimeapi.org/api/timezone/Europe/London";
HttpHeaders headers = new HttpHeaders();
headers.set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36");
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

if (MediaType.APPLICATION_JSON_UTF8.equals(response.getHeaders().getContentType())
        || MediaType.APPLICATION_JSON.equals(response.getHeaders().getContentType())) {
    // Execute logic for JSON response
} else {
    // Execute logic for other response types
}

我的查询涉及解决这个差异,并确保通过RestTemplate接收的Content-Type头部与通过Postman或curl等工具获得的头部一致。值得注意的是,为请求提供的URL受到来自最终用户的动态输入的影响,从而表明响应主体和Content-Type可能会有所不同。
我很想知道如何纠正这种情况,并通过RestTemplate始终获得正确的Content-Type。我正在寻求的解决方案应该适应URL的动态特性,并适应响应内容和Content-Type的潜在变化。
如果你能帮忙的话,我将不胜感激。

bvjveswy

bvjveswy1#

您可以通过添加Accept头来指示要处理的内容类型:

headers.set("Accept", "application/json");

PS:当执行请求时,我注意到请求并不总是成功的,所以你需要处理它。

相关问题