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

查看:292
本文介绍了如何设置“接受": 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/jsonapplication/xml,...)和请求方法(例如GETPOST,...) 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 方法/org/springframework/http/HttpEntity.html"rel =" noreferrer> HttpEntity ,您还可以为其设置

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); 

This is mentioned in the RestTemplate#postForObject Javadoc.

request参数可以是HttpEntity,以便添加其他 请求的HTTP标头.

The request parameter can be a HttpEntity in order to add additional HTTP headers to the request.

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

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