How to configure HTTP Client

Daniel S. Blanco
2 min readMay 13, 2020

--

It’s very common in Java and in modern projects to have to connect with Web Services. There are a few libraries that allow you to do that. And org.apache.httpcomponents.httpclient, is one of the most used.

Although it’s very easy to use, there are some important aspects to be aware of. And if we don’t control them, we could spend more time that we want developing it. Principally is about how to connect with Web Services with HTTPS protocol and in other domains.

In addition to this, we also have to know that HTTP Client changes how must be configured in version 4.3. There is an after and before of this version. Because of that, in this post, we are going to learn how to do it. But telling you how to do it in base on the version. And those are:

  1. Ignore SSL certificate. If you are going to connect to domains through HTTPS. But those don’t have a trusted certificate, especially in development environments. To avoid that kind of problem, we can use TrustSelfSignedStrategy.
  2. Ignore hostname verification. It’s also possible that the certificate can be wrongly generated. And the hostname isn’t contained in the domain certificate. To avoid that, we can use SSLConnectionSocketFactory and its constants ALLOW_ALL_HOSTNAME_VERIFIER.
  3. Redirection. If we’re going to do a Web Service call behind a proxy. And our client receives a 302 HTTP status code. To avoid that, we can use LaxRedirectStrategy.

Now it’s time to see the code and how we can avoid those problems. First in Http Client version 4.3 or minus:

And more importantly, the actual way. Omitting the currently deprecated classes.

--

--