Sending GET request with Authentication headers using restTemplate

前端 未结 6 1368
执念已碎
执念已碎 2021-01-31 01:20

I need to retrieve a resources from my server by sending a GET request with the some Authorization headers using RestTemplate.

After going over the docs I noticed that

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 01:49

    You can use postForObject with an HttpEntity. It would look like this:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer "+accessToken);
    
    HttpEntity entity = new HttpEntity(requestJson,headers);
    String result = restTemplate.postForObject(url, entity, String.class);
    

    In a GET request, you'd usually not send a body (it's allowed, but it doesn't serve any purpose). The way to add headers without wiring the RestTemplate differently is to use the exchange or execute methods directly. The get shorthands don't support header modification.

    The asymmetry is a bit weird on a first glance, perhaps this is going to be fixed in future versions of Spring.

提交回复
热议问题