HTTP get with headers using RestTemplate

后端 未结 2 487
别那么骄傲
别那么骄傲 2020-12-07 22:19

How can I send a GET request using the Spring RestTemplate? Other questions have used POST, but I need to use GET. When I run this, the program continues to work, but it see

2条回答
  •  心在旅途
    2020-12-07 22:37

    The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

    So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

    HttpHeaders headers = new HttpHeaders();
    headers.set("Header", "value");
    headers.set("Other-Header", "othervalue");
    ...
    
    HttpEntity entity = new HttpEntity(headers);
    
    ResponseEntity response = restTemplate.exchange(
        url, HttpMethod.GET, entity, String.class, param);
    

    Finally, use response.getBody() to get your result.

    This question is similar to this question.

提交回复
热议问题