Basically as the title says. Apache HttpClient and Spring RestTemplate allow for defining custom interceptors which wrap around requests/responses and allow for additional (global) modification of request parameters, logging, etc...
I do not see such a feature available in standard Java implementation of java.net.http.HttpClient
(as of Java 11). Am I missing something or is there no way to intercept all requests/responses on a single HttpClient
?
Once created, an HttpClient instance is immutable, thus automatically thread-safe, and you can send multiple requests with it. By default, the client tries to open an HTTP/2 connection. If the server answers with HTTP/1.1, the client automatically falls back to this version.
Interceptors are those which helps to obstruct or change requests or responses. Protocol interceptors in general act upon a specific header or a group of related headers. HttpClient library provides support for interceptors.
You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution. Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.
There isn't a built-in solution, but you can write your own code as in this answer or use this interceptable-http-client library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With