3 Ways to send a HTTP GET and POST request in Java? JDK 11 HttpClient Example tutorial

Hello guys, today's word is of modern web applications and APIs and in this world the ability to communicate with remote servers is an essential skill for Java developers. Whether you need to retrieve data from a web service or send data to a server for processing, mastering the art of making HTTP requests is crucial. If you are a Java developer the you must know how to send HTTP requests and parse HTTP Response to work effectively on different kind of Java web applications. If you don't know then don't worry as In this comprehensive guide, we will walk you through the fundamental concepts and practical techniques for sending HTTP GET and POST requests in Java. Whether you're a beginner looking to learn the basics or an experienced developer seeking to refine your skills, this tutorial will equip you with the knowledge and tools to interact with web services effectively using Java.

We will explore the key libraries and classes available in the Java ecosystem that simplify the process of making HTTP requests, and we'll provide real-world examples to illustrate how to put these concepts into practice. By the end of this guide, you'll have a solid foundation in making HTTP requests in Java, enabling you to seamlessly integrate your applications with external APIs and web services.

In Java, there are several libraries available for sending HTTP requests, including the popular Apache HttpClient library and the built-in java.net.HttpURLConnection class and recently added new HttpClient library which is available from Java SE 11. We will see example of all of them so that you know different ways to send HTTP GET and POST Request in Java. 

So, let's dive in and uncover the intricacies of sending HTTP GET and POST requests in Java, empowering you to build more dynamic and interconnected applications.


3 Ways to Send HTTP Request from Java with Example

As I said there are multiple ways to send different types of HTTP request in Java like GET, PUT, POST, and DELETE and here we will see three main ways, first using new HTTPClient library, second using old HttpURLConnection which you can use if you are not using Java SE 11 and third and most flexible Apache HttpClieint third party library which you can use with any Java version

So let's start with new HttpClient library which should be your preferred method if you are running on Java SE 11 or higher version

3 Ways to send a HTTP GET and POST request in Java



How to send GET request in Java using HttpClient library of JDK 11

To send an HTTP GET request in Java using the HttpClient library, you can use the following code example. Note that as of my last knowledge update in September 2021, HttpClient was introduced in Java 11. If you're using an older Java version, consider upgrading to Java 11 or higher or use a third-party library like Apache HttpClient.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpGetExample {

    public static void main(String[] args) {
        // Create an instance of the HttpClient
        HttpClient httpClient = HttpClient.newHttpClient();

        // Define the URL for the GET request
        String url = "https://example.com/api/data"; // Replace with your target URL

        // Build the HTTP GET request
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET()
                .build();

        try {
            // Send the GET request and retrieve the response
            HttpResponse<String> response = httpClient.send(request,
    HttpResponse.BodyHandlers.ofString());

            // Check the HTTP status code
            int statusCode = response.statusCode();
            System.out.println("HTTP Status Code: " + statusCode);

            // Print the response body
            String responseBody = response.body();
            System.out.println("Response Body:");
            System.out.println(responseBody);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}


In this code:
  • We import the necessary classes from the java.net.http package.
  • We create an instance of the HttpClient class.
  • We specify the URL you want to send the GET request to.
  • We build the HTTP GET request using the HttpRequest.newBuilder() method.
  • We send the request using httpClient.send(), specifying the response body handler as HttpResponse.BodyHandlers.ofString() to handle the response as a string.
  • We check the HTTP status code and print the response body.
  • Remember to replace "https://example.com/api/data" with the actual URL you want to request data from.

Now, let's see how to send POST request using HttpClient library in Java.


How to send POST request in Java using HttpClient library?

To send an HTTP POST request in Java using the HttpClient library, you can use the following code example. This code assumes you have already imported the necessary classes and initialized the HttpClient as shown in the previous example:

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

public class HttpPostExample {

    public static void main(String[] args) {
        // Create an instance of the HttpClient
        HttpClient httpClient = HttpClient.newHttpClient();

        // Define the URL for the POST request
        String url = "https://example.com/api/post"; // Replace with your target URL

        // Define the POST data (key-value pairs)
        Map<String, String> postData = new HashMap<>();
        postData.put("param1", "value1");
        postData.put("param2", "value2");

        // Build the HTTP POST request with form data
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/x-www-form-urlencoded") 
// Set the content type
                .POST(HttpRequest.BodyPublishers.ofString(buildFormDataString(postData))) 
// Build and set the request body
                .build();

        try {
            // Send the POST request and retrieve the response
            HttpResponse<String> response = httpClient.send(request,
 HttpResponse.BodyHandlers.ofString());

            // Check the HTTP status code
            int statusCode = response.statusCode();
            System.out.println("HTTP Status Code: " + statusCode);

            // Print the response body
            String responseBody = response.body();
            System.out.println("Response Body:");
            System.out.println(responseBody);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    // Helper method to build a URL-encoded form data string from a map
    private static String buildFormDataString(Map<String, String> data) {
        StringBuilder formData = new StringBuilder();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            formData.append(entry.getKey());
            formData.append("=");
            formData.append(entry.getValue());
            formData.append("&");
        }
        // Remove the trailing "&"
        formData.setLength(formData.length() - 1);
        return formData.toString();
    }
}

In this code:
  • We define the URL for the POST request and the POST data as a Map of key-value pairs.
  • We build the HTTP POST request using HttpRequest.newBuilder(), specifying the URL, content type, and request method.
  • We use the HttpRequest.BodyPublishers.ofString() method to set the request body with the URL-encoded form data.
  • We send the POST request and handle the response similar to the GET request example.
  • Make sure to replace "https://example.com/api/post" with the actual URL you want to send the POST request to, and customize the postData map with your own data.

How to send GET request using HttpURLConnection in Java

Here's an example of how to send a GET request using HttpURLConnection:

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;


public class HttpGetExample {

public static void main(String[] args) {

try {

URL url = new URL("https://www.example.com");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("GET");



int responseCode = con.getResponseCode();

System.out.println("Response code: " + responseCode);



BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

in.close();



System.out.println(response.toString());

} catch (IOException e) {

e.printStackTrace();

}

}

}


How to Send a POST request using HttpURLConnection in Java

And here's an example of how to send a POST request using HttpURLConnection

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;


public class HttpPostExample {

public static void main(String[] args) {

try {

URL url = new URL("https://www.example.com");

HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestMethod("POST");

con.setDoOutput(true);



DataOutputStream out = new DataOutputStream(con.getOutputStream());

out.writeBytes("param1=value1&param2=value2");

out.flush();

out.close();



int responseCode = con.getResponseCode();

System.out.println("Response code: " + responseCode);



BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;

StringBuilder response = new StringBuilder();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

in.close();



System.out.println(response.toString());

} catch (IOException e) {

e.printStackTrace();

}

}

}



How to Send a POST request using Apache HttpClient in Java?

Here is a complete example of how to send a POST request using Apache HttpClient:

import java.util.ArrayList;

import java.util.List;


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.HttpPost;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;


public class HttpPostExampleApache {

public static void main(String[] args) {

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost("https://www.example.com");

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair("param1", "value1"));

params.add(new BasicNameValuePair("param2", "value2"));

try {

httpPost.setEntity(new UrlEncodedFormEntity(params));

CloseableHttpResponse response = httpClient.execute(httpPost);

System.out.println("Response code: " + response.getStatusLine().getStatusCode());

response.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

httpClient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

It is worth noting that the Apache HttpClient library offers a more robust and flexible way of sending HTTP requests compared to java.net.HttpURLConnection. However, it also has a steeper learning curve and is more verbose.



GET request using Apache HttpClient

Here is a complete example of how to send a GET request using Apache HttpClient:

import java.io.IOException;


import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;


public class HttpGetExampleApache {

public static void main(String[] args) {

CloseableHttpClient httpClient = HttpClients.createDefault();

HttpGet httpGet = new HttpGet("https://www.example.com");

try {

CloseableHttpResponse response = httpClient.execute(httpGet);

System.out.println("Response code: " + response.getStatusLine().getStatusCode());

response.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

httpClient.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}


Summary

In this guide, we've explored the fundamentals of sending HTTP GET and POST requests in Java using the HttpClient library as well as HttpURLConnection and Apache HttpClient library. By default you should always be using the HttpClient library of JDK 11. This powerful library, introduced in Java 11, provides a straightforward and flexible way to interact with web services and APIs, making it an essential tool for modern Java developers.

For sending an HTTP GET request,  you can follow below steps:
  • Create an instance of HttpClient.
  • Define the target URL.
  • Build the HTTP GET request using HttpRequest.newBuilder().
  • Send the request and handle the response.

For sending an HTTP POST request, we covered the following steps:
  • Create an instance of HttpClient.
  • Define the target URL.
  • Prepare the POST data as key-value pairs.
  • Build the HTTP POST request with the appropriate headers and request method.
  • Send the request with the POST data as the request body.
  • Handle the response.

Mastering these techniques allows you to seamlessly integrate your Java applications with external web services and APIs, enabling data retrieval, submission, and interaction with remote resources. Whether you're building web applications, microservices, or automation scripts, the ability to communicate over HTTP is a fundamental skill.


That's all about 3 ways to send HTTP GET and POST request in Java. We have seen all three ways, I mean HttpClient library, old HttpURLConnection and ubiquitous Apache HttpClient library. These codes are fairly straightforward. You create an instance of CloseableHttpClient and then use it to execute an instance of HttpGet with a specified URL. The response code of the HTTP request is printed to the console. You can add request headers, set the request entity, and read the response entity as well.

As you continue your journey in Java development, remember to stay updated with the latest features and best practices in the ever-evolving landscape of web development and APIs. The HttpClient library, with its simplicity and versatility, will remain a valuable tool in your toolbox for years to come.

Now that you have a solid understanding of sending HTTP requests in Java, you can explore more advanced topics, such as handling authentication, error handling, and working with JSON data, to enhance your web communication capabilities.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.