1

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

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.