HTTPClients are reusable

Hi 👋,

I wanted to write this article to tell you that instantiating a HttpClient class is often a costly operation.

If you have a method that does something like:

public class Main {
  static void myMethod() {
    HttpClient client = new HttpClient()
    // do stuff
  }
}

You should refactor it ASAP. Either move the HttpClient into the class and perhaps ensure that the class is a Singleton or retrieve the HttpClient instance using an Object Pool pattern like the HttpClient class from System.Net.Http.

The HttpClient class instance acts as a session to send HTTP requests. An HttpClient instance is a collection of settings applied to all requests executed by that instance. In addition, every HttpClient instance uses its own connection pool, isolating its requests from requests executed by other HttpClient instances.

Thanks for reading!

Further reading

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.