如何通过Spring发送带标头的GET请求

时间:2014-07-02 14:59:52

标签: spring rest java-ee

它将使用GET请求调用另一个REST API。

@RequestMapping(value = "xxxx/{id}", method = RequestMethod.GET)
public @ResponseBody GetObjet GET( @PathVariable("id") String id,
                @RequestHeader(value="X-Auth-Token") String Token) {

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();        
    headers.add("X-Auth-Token", Token);

    HttpEntity entity = new HttpEntity(headers);
    ResponseEntity<GetObjet> response = restTemplate.exchange(url, HttpMethod.GET, entity, GetObjet.class);

    return response.getBody();
}

总是400错误。这意味着请求正文中的错误请求或一些错误。但这是GET,所以resquest bodys总是空的。所以这种添加标题的方式可能不对。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以在方法中获取包含符号@RequestHeader的标题

public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive)  {

}

o

You can read more about the request here

获取网址的另一种方法是:

 @RequestMapping(value = "/restURL")
     public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){
     //Use headers to get the information about all the request headers
     long contentLength = headers.getContentLength();
    ...
     StreamSource source = new StreamSource(new StringReader(body));
     YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
     ...
     }

答案 1 :(得分:0)

尝试使用:

RestTemplate.getForEntity(url, GetObject.class);

您有一些方法可以从其他API请求数据,例如getForEntitygetForObject,使用您需要的方法。