如何在 Spring RestTemplate 请求上设置“接受:”标头?

新手上路,请多包涵

我想在使用 Spring 的 RestTemplate 发出的请求中设置 Accept: 的值。

这是我的 Spring 请求处理代码

@RequestMapping(
    value= "/uom_matrix_save_or_edit",
    method = RequestMethod.POST,
    produces="application/json"
)
public @ResponseBody ModelMap uomMatrixSaveOrEdit(
    ModelMap model,
    @RequestParam("parentId") String parentId
){
    model.addAttribute("attributeValues",parentId);
    return model;
}

这是我的 Java REST 客户端:

 public void post(){
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("parentId", "parentId");
    String result = rest.postForObject( url, params, String.class) ;
    System.out.println(result);
}

这对我有用;我从服务器端得到一个 JSON 字符串。

My question is: how can I specify the Accept: header (eg application/json , application/xml , … ) and request method (eg GET , POST , … ) 当我使用 RestTemplate 时?

原文由 edaklij 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 712
2 个回答

我建议使用 exchange HttpEntity 方法之一,您还可以为其设置 HttpHeaders (您还可以指定要使用的 HTTP 方法。)

例如,

 RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntity<String> entity = new HttpEntity<>("body", headers);

restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

我更喜欢这个解决方案,因为它是强类型的,即。 exchange 期望一个 HttpEntity

但是,您也可以将 HttpEntity 作为 request 参数传递给 postForObject

 HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class);

这在 RestTemplate#postForObject Javadoc 中提到。

request 参数可以是 HttpEntity 以便向 请求添加额外的 HTTP 标头

原文由 Sotirios Delimanolis 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以在 RestTemplate 中设置拦截器“ClientHttpRequestInterceptor”,以避免每次发送请求时都设置标头。

 public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {

        private final String headerName;

        private final String headerValue;

        public HeaderRequestInterceptor(String headerName, String headerValue) {
            this.headerName = headerName;
            this.headerValue = headerValue;
        }

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().set(headerName, headerValue);
            return execution.execute(request, body);
        }
    }

然后

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(interceptors);

原文由 Ammar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题