java / intermediate
Snippet
Injecting Auth Headers with RestTemplate Interceptors
Interceptors in RestTemplate allow you to apply logic to all outgoing HTTP requests globally. This is ideal for adding authentication tokens, logging request payloads, or handling custom error logic without repeating it at every call site.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class AuthInterceptor implements ClientHttpRequestInterceptor {@Overridepublic ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {request.getHeaders().add("Authorization", "Bearer " + getToken());return execution.execute(request, body);}private String getToken() { return "secret-token"; }}@Beanpublic RestTemplate restTemplate() {RestTemplate restTemplate = new RestTemplate();restTemplate.setInterceptors(Collections.singletonList(new AuthInterceptor()));return restTemplate;}
spring
Breakdown
1
ClientHttpRequestInterceptor
The interface used to intercept and modify outbound client-side HTTP requests.
2
execution.execute(request, body)
Continues the request chain after the interceptor logic is applied.
3
setInterceptors(...)
Registers the list of interceptors to be used by the RestTemplate instance.