HttpClient: Making HTTP Requests in Java Applications Easy and Explained

Discover how Apache HttpClient enhances your Java applications with effortless HTTP communication. Our blog post guides you through using GET and POST requests with practical examples. Learn how to quickly and efficiently send HTTP requests directly from your Java code.

Apache HttpClient

Apache HttpClient is widely used to send HTTP requests directly from a Java program. Using Maven makes integrating Apache HttpClient into your project a breeze. Simply add the following dependencies:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.4</version>
</dependency>

If you are not using Maven, add the following JAR files to your project path:

  • httpclient-4.4.jar
  • httpcore-4.4.jar
  • commons-logging-1.2.jar
  • commons-codec-1.9.jar

Using Apache HttpClient

The following steps are necessary to use Apache HttpClient for GET and POST requests:

  1. Create an instance of CloseableHttpClient using the helper class HttpClients.
  2. Create an instance of HttpGet or HttpPost based on the type of HTTP request.
  3. Add required headers like User-Agent, Accept-Encoding, etc.
  4. For POST requests: Create a list of NameValuePair and add all form parameters. Then set these in the HttpPost entity.
  5. Obtain CloseableHttpResponse by executing the HttpGet or HttpPost request.
  6. Get the required details like status code, error information, response HTML, etc. from the response.
  7. Finally, close the Apache HttpClient resource.

Example Program

Here is the final program that shows how to use Apache HttpClient to execute HTTP GET and POST requests in a Java program:

package com.journaldev.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class ApacheHttpClientExample {

    private static final String USER_AGENT = "Mozilla/5.0";

    private static final String GET_URL = "https://localhost:9090/SpringMVCExample";

    private static final String POST_URL = "https://localhost:9090/SpringMVCExample/home";

    public static void main(String[] args) throws IOException {
        sendGET();
        System.out.println("GET DONE");
        sendPOST();
        System.out.println("POST DONE");
    }

    private static void sendGET() throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(GET_URL);
        httpGet.addHeader("User-Agent", USER_AGENT);
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);

        System.out.println("GET Response Status:: "
                + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        // print result
        System.out.println(response.toString());
        httpClient.close();
    }

    private static void sendPOST() throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(POST_URL);
        httpPost.addHeader("User-Agent", USER_AGENT);

        List urlParameters = new ArrayList();
        urlParameters.add(new BasicNameValuePair("userName", "Pankaj Kumar"));

        HttpEntity postParams = new UrlEncodedFormEntity(urlParameters);
        httpPost.setEntity(postParams);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

        System.out.println("POST Response Status:: "
                + httpResponse.getStatusLine().getStatusCode());

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpResponse.getEntity().getContent()));

        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();

        // print result
        System.out.println(response.toString());
        httpClient.close();
    }

}

Result

When the program is executed, you will receive similar HTML as in the browser:

GET Response Status:: 200
<html><head><title>Home</title></head><body><h1>Hello world!</h1><P>The time on the server is March 7, 2015 1:01:22 AM IST.</P></body></html>
GET DONE
POST Response Status:: 200
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Home Page</title></head><body><h3>Hi Pankaj Kumar</h3></body></html>
POST DONE

Conclusion

This was our guide to the example with Apache HttpClient. It includes many useful methods that you can use. Therefore, I recommend trying them out for a better understanding.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

centron Managed Cloud Hosting in Deutschland

Standardize Configuration File Names for Log4j

Apache, Guide
Standardize Configuration File Names for Log4j Log4j expects configuration files to have standard names. If your files are named differently, such as myapp-log4j.xml or myapp-log4j.properties, log4j will not recognize them…