Simple Java API Caller Using Apache HttpClient

Building a Simple Java API Caller Using Apache HttpClient — A Beginner‑Friendly Guide

When working with backend systems, automation scripts, or integration services, one of the most common tasks is sending API requests from Java. Although modern libraries like OkHttp and Spring WebClient are popular today, many legacy systems still rely on Apache HttpClient — a stable and widely‑used HTTP library.

In this blog, we’ll walk through a simple Java example that reads data from a file, sends it as an API request, and prints the response. This is a great starting point if you’re learning Java‑based API automation or maintaining older enterprise applications.

Why Apache HttpClient?

Apache HttpClient has been around for years and is known for:

  • Easy request/response handling

  • Support for headers, payloads, and authentication

  • Compatibility with older Java applications

  • Simple debugging and logging

Even though it’s now considered a legacy library, many organisations still use it in production systems.

Understanding the Code

Below is a simplified version of the Java class that performs three main tasks:

  1. Reads data from a file

  2. Sends an HTTP POST request

  3. Reads the API response

Let’s break it down step by step.

1. Creating the HttpClient

java
HttpClient httpClient = new DefaultHttpClient();

This creates a client instance that will be used to send the request. Although DefaultHttpClient is deprecated in newer versions, it is still common in older Java projects.

2. Reading Data From a File

java
BufferedReader in = new BufferedReader(new FileReader(filepath));
while ((request = in.readLine()) != null) {
    System.out.println(request);
}
in.close();

Here’s what happens:

  • The program reads the file line by line

  • Each line is printed (useful for debugging)

  • The final value is stored in the request variable, which becomes the API payload

This is useful when your API request body is stored externally (JSON, XML, etc.).

3. Sending the API Request

java
HttpPost hitrequest = new HttpPost(url);
StringEntity params = new StringEntity(request);
hitrequest.addHeader("custom", "value");
hitrequest.setEntity(params);
HttpResponse response = httpClient.execute(hitrequest);

What’s happening here?

  • HttpPost creates a POST request

  • StringEntity wraps the request body

  • A custom header is added

  • The request is executed using httpClient.execute()

This is the core part where the API call is made.

4. Reading the API Response

java
BufferedReader r = new BufferedReader(
    new InputStreamReader(response.getEntity().getContent())
);

This reads the response stream from the server. You can extend this to print or parse the response.

5. Closing the Connection

java
finally {
    httpClient.getConnectionManager().shutdown();
}

This ensures the connection is properly closed, preventing memory leaks.

Complete Code Overview

Here’s the full structure in a readable format:

java
public class Common {
    public static ArrayList<Object> API() {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            // Find current directory
            String workingdirectory = System.getProperty("user.dir");

            // Read data from file
            BufferedReader in = new BufferedReader(new FileReader(filepath));
            while ((request = in.readLine()) != null) {
                System.out.println(request);
            }
            in.close();

            // Send API request
            HttpPost hitrequest = new HttpPost(url);
            StringEntity params = new StringEntity(request);
            hitrequest.addHeader("custom", "value");
            hitrequest.setEntity(params);

            HttpResponse response = httpClient.execute(hitrequest);

            BufferedReader r = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent())
            );

        } catch (Exception ex) {
            System.out.println(ex);
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

Best Practices & Improvements

If you plan to use this in a real project, consider the following upgrades:

✔ Use CloseableHttpClient instead of DefaultHttpClient

It’s modern and actively supported.

✔ Add proper exception handling

Log errors instead of printing them.

✔ Use try‑with‑resources

Automatically closes streams.

✔ Validate file paths and URLs

Avoid runtime failures.

✔ Parse the response

Convert JSON/XML into objects using libraries like Jackson or Gson.

Final Thoughts

This simple example demonstrates how Java can read data from a file and send it as an API request using Apache HttpClient. It’s a great starting point for beginners working on automation, backend integration, or legacy system maintenance.


Comments