HTTP Client Basics – Get Request

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.

compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.7'

Making a Basic GET Request

HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(new HttpGet("http://dummy.restapiexample.com/api/v1/employees"));

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

int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

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.

String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);

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.

Header header = new BasicHeader(
HttpHeaders.CONTENT_TYPE, "application/json");
List<Header> headers = new ArrayList<>();
headers.add(header);
HttpClient client = HttpClientBuilder.create().setDefaultHeaders(headers).build();

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.

int timeout = 5;
RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(timeout * 100)
                .setConnectionRequestTimeout(timeout * 100)
                .setSocketTimeout(timeout * 100).build();
HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultHeaders(headers).build();

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

@Test
public void getTest() throws IOException {

//Set Timeout
        int timeout = 5;
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(timeout * 1000)
                .setConnectionRequestTimeout(timeout * 1000)
                .setSocketTimeout(timeout * 1000).build();
//Set Headers
        Header header = new BasicHeader(
        HttpHeaders.CONTENT_TYPE, "application/json");
        List<Header> headers = new ArrayList<>();
        headers.add(header);

//Create HTTP Client
        HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).setDefaultHeaders(headers).build();
        HttpResponse response = client.execute(new HttpGet("http://dummy.restapiexample.com/api/v1/employees"));

//Extract the status code and body       
        int statusCode = response.getStatusLine().getStatusCode();
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println("Body: " +responseBody);
        System.out.println("Status Code: " +statusCode);

}

Happy Coding!

Leave a Comment

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