Tutorials  /  Java

HttpClient: Making HTTP Requests in Java Applications Easy and Explained

Ccentron Redaktion · October 2024 ·3 min read ·Java, Tutorial

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:

Code
<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
VM

Matching infrastructure at centron

Java applications in continuous operation: ccloud³ VMs from €3.12 per month with full root access, billed by the hour. Rent a cloud server →

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:

Go
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:

Code
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.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Java
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren