12

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?

Bobulous
  • 12,967
  • 4
  • 37
  • 68
MrPlow
  • 1,295
  • 3
  • 26
  • 45
  • It seems like you can accomplish each of those things with one or two lines of code. Are you just looking for a Spring-like way to do them? – VGR Dec 10 '18 at 16:14
  • @VGR one or two additional lines of code for each request? The only way I currently imagine I could modify/log all requests/responses of a `HttpClient` without duplicating code is to wrap `HttpClient` into a custom class and implement interceptors around all `send` calls myself. If I'm missing something obvious please let me know. – MrPlow Dec 11 '18 at 07:14
  • If you want a special “global” method that is magically called whenever any instance of HttpClient executes, you want a Spring-like way of doing it. Otherwise, you’re correct; you log each usage of an HttpClient instance, just as you would do when using an instance of any other Java SE class. If you have a great many HttpClient calls, making a wrapper class isn’t a bad idea. – VGR Dec 11 '18 at 14:44
  • 1
    I think it is pretty sad that nowadays such absolutely useful features don't make their way into Java SE. Maybe I want to create a little app that fetches data from a REST endpoint without adding a full-blown Spring, CDI (or whatever EE) environment. And yes - there are client libs for REST calls but why shouldn't Java SE be able to accomplish this task? – downdrown Sep 04 '20 at 16:09

1 Answers1

3

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.

bowsersenior
  • 12,524
  • 2
  • 46
  • 52