In this article, we will learn how to do the GET request by using the HTTP Client.

We are a software testing blog. We mostly provide articles on testing but there is a lot to explore on development ecosystem. So we started to wring about Java 8 stuff like File APIs and DateTime APIs. Now we want to write about the HTTPClient API. But why?

We are using many API automation libraries like RestAssured. But what happens when we make a get request? What’s going on underneath of it? Do you know? Some of us know some of us don’t know. So we decided to tell you a bit about HTTPClient 4.

RestAssured or any other API automation library is a wrapper built on top of HttpClient. So you don’t deal with low-level issues. Let’s see how HTPPClient 4 version is working with basic examples.

Dependency

You need to add below dependency into your project.

Making a Basic GET Request

We created a HttpClient object then executed a GET request.  It returns a HttpResponse object. Now let’s extract the status code.

You see, it’s very easy.

Extract Response Body

Let’s extract the body of the response. For this, you need to use EntityUtils so you can extract the body from the response object.

Setting Headers to Request

Maybe you might want to set a header. Let’s add Content-Type header to that request. The setDefaultHeaders method takes a  Collection as a parameter that’s why you need to create a pass a List of Headers.

HttpHeaders class gives you the ability to use the most common content type by its static variables. As you can see, there are many predefined values.

Setting Timeout to Request

It would be a best practice to set a timeout threshold to your request.

Now, if the request is not completed in 500ms, your test will fail with a TimeOutException.

Here’s the full code for this simple GET request

Happy Coding!