小编典典

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

spring

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

这是我的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字符串。

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


阅读 2181

收藏
2020-04-12

共1个答案

小编典典

我建议使用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#postForObjectJavadoc中提到了这一点。

该request参数可以是a HttpEntity,以便向请求中添加其他HTTP标头。

2020-04-12