如何设置“接受:"Spring RestTemplate 请求的标头? [英] How to set an "Accept:" header on Spring RestTemplate request?

查看:46
本文介绍了如何设置“接受:"Spring RestTemplate 请求的标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set the value of the Accept: in a request I am making using Spring's RestTemplate.

这是我的 Spring 请求处理代码

Here is my Spring request handling code

@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 客户端:

and here is my Java REST client:

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 字符串.

This works for me; I get a JSON string from the server side.

我的问题是:如何指定 Accept: 标头(例如 application/json,application/xml, ... )和请求方法(例如 GET,POST, ... )当我使用 RestTemplate 时?

My question is: how can I specify the Accept: header (e.g. application/json,application/xml, ... ) and request method (e.g. GET,POST, ... ) when I use RestTemplate?

推荐答案

我建议使用 exchange 接受 HttpEntity 您也可以为其设置 HttpHeaders.(您也可以指定要使用的 HTTP 方法.)

I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.)

例如

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.

I prefer this solution because it's strongly typed, ie. exchange expects an HttpEntity.

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

However, you can also pass that HttpEntity as a request argument to postForObject.

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

这在 RestTemplate#postForObject Javadoc.

This is mentioned in the RestTemplate#postForObject Javadoc.

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

这篇关于如何设置“接受:"Spring RestTemplate 请求的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆