DONG
DONG

Reputation: 69

How to send GET request with headers by Spring

It will call another REST API with a GET request.

@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();
}

Always 400 Error. It means that bad request or some errors in the request body. But this is GET so the resquest bodys is always empty. So this way to add header may be not right. Any ideas?

Upvotes: 2

Views: 3401

Answers (2)

Benjamin RD
Benjamin RD

Reputation: 12044

You can obtain the headers including the notation @RequestHeader in your method

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

}

o

You can read more about the request here

And the other way to abtain the URL is:

 @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);
     ...
     }

Upvotes: 1

Genzotto
Genzotto

Reputation: 1974

Try using:

RestTemplate.getForEntity(url, GetObject.class);

You have some methods to request data from a rest API, such as getForEntity and getForObject, use the one you needed.

Upvotes: 0

Related Questions