HowTo: Apache HttpClient 5

Daniel S. Blanco
2 min readJan 18, 2023

--

We have already done other posts about this great library, about configuration and use of the Fluent interface. Today we will see a basic manual about the new version, HTTP Client 5 in its classic version. And four simple examples for its most common use.

We will see the most basic and complete example, with an HTTP Post call. In 5 simple steps, we can invoke the method and get its response. Even methods that do not need to send data, such as GET or DELETE can be done in even fewer steps.

The next point is to add a CookieStore that allows us to store the cookies that the server sends us through the header ‘set-cookie’. And that allows us to return this cookie to the server. Very useful for the cases in which a communication with the server is needed, especially for login access.

Now we will see how to make a call with user and password authentication. And although you can always add the header by hand in the HTTP method, this library has its own classes that allow you to perform the authentication in a more secure way.

With BasicCredentialsProvider, the web client will not attach the authentication header unless it receives a 401 request code. Here we can see a test of how it works with Wiremock.

The last example will be to create a client that will invoke any endpoint with a self-signed and therefore untrusted certificate. Needless to say, although this is very useful in development environments, it should never be done in production environments.

--

--

No responses yet