1
votes

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

1
What have you try so far? Could you please post Minimal, Complete, and Verifiable example? - Szymon Stepniak

1 Answers

1
votes

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