Reputation: 83
I am writing a java client for a protected api service using Apache's HttpClient. I was wondering if it is possible to add a dynamic header to each request automatically instead of having to add the header on every HttpGet or HttpPost instance. The header needs to take the request URL and the request method (GET or POST), because of this requirement I cannot just simply add it to the default request headers when building the HttpClient. Thanks
Upvotes: 1
Views: 2258
Reputation: 27558
Use custom request interceptor
CloseableHttpClient client = CachingHttpClients.custom()
.addInterceptorLast((HttpRequestInterceptor) (request, context) -> {
String method = request.getRequestLine().getMethod();
String requestUri = request.getRequestLine().getUri();
request.addHeader("x-my-header", doSomethingClever(method, requestUri));
})
.build();
Upvotes: 1