POST 请求未在 RestTemplate 中添加请求 headers

POST request doesn't add requested headers in 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。我的代码是缺少什么还是我做的完全错了?提前致谢

您不能像现在这样设置 header,您需要将请求包装在 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 header 附加到每个请求。然后,您可以在 RestTemplate:

上进行设置
restTemplate.setInterceptors(new LinkedList<>(new MyTokenHeaderAddingInterceptor()));

这将使您不必记住为每个请求发送 header。