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

问题描述 投票:0回答:1

在提供的代码片段中,我使用 Spring 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 的潜在变化。

如有任何帮助,我们将不胜感激。

java spring spring-boot spring-mvc resttemplate
1个回答
0
投票

您可以通过添加

Accept
标头来指示要处理的内容类型:

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

PS:在执行请求时,我注意到请求并不总是成功,因此您需要处理它。

© www.soinside.com 2019 - 2024. All rights reserved.