POST请求不会在RestTemplate中添加请求的标头

时间:2015-02-12 10:59:31

标签: java rest post resttemplate

我必须通过发送POST请求获得User

POST http://myurl.com/rest/user/getbyusername/{user} HTTP/1.0 token: uonIQz8WNE7UB5iR2V0ZYQ== User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0;) Pragma: no-cache Content-Length: 0 Host: myurl.com

我正在尝试使用这段代码:

private User getByUsername(String username) {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    List<String> list = new ArrayList<>();
    list.add(Params.token);
    headers.put("token", list);
    return restTemplate.postForObject("http://myurl.com/rest/user/getbyusername/{username}", headers, User.class,
            username);
}

控制器:

@ResponseBody
@RequestMapping(value = "getbyusername/{username}", 
                produces = "application/json", 
                method=RequestMethod.POST)
public String getByUsername(@PathVariable("username") 
                String username, HttpServletRequest request)
        throws IOException {
    if (!request.getHeader(headerName).isEmpty() && StringUtils.isNotBlank(token)
            && request.getHeader(headerName).equals(token)) {...}
}

可悲的是结果是Error 404。我的代码缺少某些东西还是我完全错了?提前致谢

1 个答案:

答案 0 :(得分:2)

您无法像目前那样设置标头,您需要将请求包装在HttpEntity中,例如:

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.set("token", Params.token);

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

restTemplate.postForObject("http://myurl.com/rest/user/getbyusername/{username}",
        entity,
        User.class);

postForObject Javadocs中建议采用这种方法。

或者,您可以实现ClientHttpRequestInterceptor,它会将token标头附加到每个请求。然后,您可以在RestTemplate

上设置此项
restTemplate.setInterceptors(new LinkedList<>(new MyTokenHeaderAddingInterceptor()));

这样可以避免记住为每个请求发送标题。