在 Spring 中添加接受 header

Adding Accept header in Spring

我正在尝试在我的 Spring RESTful 应用程序中使用来自 http://www.foaas.com/ 的 JSON object。然而,他们需要与 Accept header.

进行内容协商

我已经尝试过在 SO 上找到的这个方法:

RestTemplate restTemplate = new RestTemplate();

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

HttpEntity entity = new HttpEntity(headers);

HttpEntity response = restTemplate.exchange(foaasURI, HttpMethod.GET, entity, String.class);

我每次尝试都被 403 禁止。

使用 Postman 添加接受 header 工作正常,所以我知道 foaas 端的一切都是正确的。我该如何进行?

使用HttpHeaders#setAccept

headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

问题不在于 "application/json" header。您当前的代码已成功添加 "application/json" header.

由于某些身份验证问题,服务器正在拒绝您的请求。

A 403 response generally indicates one of two conditions:

Authentication was provided, but the authenticated user is not permitted to perform the requested operation.

请参考这个link

您似乎应该在 foass.com 的请求中指定一个用户代理 header。

headers.set("User-Agent", "eltabo");

RestTemplate 默认请求工厂 (SimpleClientHttpRequestFactory) 未为其请求指定任何 user-agent。

希望对您有所帮助。