如何设置“接受": Spring RestTemplate请求上的标头? [英] How to set an "Accept:" header on Spring RestTemplate request?
问题描述
我想在使用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
方法/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 aHttpEntity
in order to add additional HTTP headers to the request.
这篇关于如何设置“接受": Spring RestTemplate请求上的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!