Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to intercept Java 11 HttpClient requests?

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?

like image 789
MrPlow Avatar asked Dec 10 '18 14:12

MrPlow


People also ask

Is Java 11 HttpClient thread-safe?

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.

What is interceptor in HttpClient?

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.

Do we need to close HttpClient in Java?

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.


1 Answers

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.

like image 160
bowsersenior Avatar answered Sep 18 '22 19:09

bowsersenior