How to Send HTTP Request from Java Program - Example Tutorial

If you are thinking is it possible to send an HTTP request from a Java program and if yes, how to send a simple HTTP GET request in Java, then you have come to the right place. In this article, I'll show you how you can use the HttpURLConnection class from java.net package to send a simple HTTP request in Java. But, first let me answer your first question, is it possible to send HTTP request in Java? Yes, it's possible and you can send any kind of HTTP request e.g. GET, POST, PUT, DELETE, HEAD, or PATCH. The java.net package provides a class called HttpURLConnection, which can be used to send any kind of HTTP or HTTPS request from Java program.


Even though the class is very powerful and support all advanced feature of HTTP protocol e.g. you can add query parameters, you can add timeouts, you can attach cookies, and you can send HTTP POST request.

For the sake of simplicity and get the ball rolling, I'll only show you how to send a GET request and retrieve data in your Java program. To make it a little bit interesting, we'll access Google's Github profile by writing a Java program.

Once you successfully write and execute this program, you can do more adventurous things with HTTP in Java by sending POST request, attaching headers, request parameters and cookies on your request.


Here is our Java program:

package tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 
 * A simple example to send HTTP request from Java
 *
 */
public class HttpDemo {

  public static void main(String args[]) throws IOException {

    URL url = new URL("https://api.github.com/users/google");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");

    BufferedReader in = new BufferedReader(new InputStreamReader(
        con.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      System.out.println(inputLine);
    }

    in.close();
  }
}

You can see that program is really simple and if you look at the import we have used just a couple of classes e.g. HttpURLConnection and URL from java.net package and InputStreamReader and BufferedReader form java.io package.

We have also used String but that's from the java.lang package so it will not appear in the import statement. If you remember, all classes from the java.lang package is automatically imported into any Java program.


Anyway, if you look at the code, you will see that we have created an URL to connect to https://api.github.com/users/google, which is google's Github profile.

After that, we have called the URL.openConnection() method which returns an HttpURLConnection. Once you got this object, you can see various fields e.g. request method, headers, request parameters and cookies, but for now, we have just set the request method as a GET.

So far, we only have things ready, HTTP connection is not made yet. The connection will be open when we call the getInputStream() on HttpURLConnection object as shown below:

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

We have wrapped the InputStream into a BufferedReader for fast and effective reading, the InputStreamReader is used to convert a stream to Reader in Java.

Since we are converting binary data to text, a character encoding will be used which will be platform's default character encoding in this case.

Anyway, once you got the BufferedReader setup, it's time to read the response. Well, you can also test the response code before reading response using below code:

int code = con.getResponseCode();

The code in the range of 200 means success, 400 means client-side error and 500 means server-side error.

In our program, we are not checking response code but just reading the response line by line, just like we read a file line by line in Java. You can see the content of Google's Github profile is printed on the console.

Something like:
A Simple Example to Send HTTP Request from Java Program


That's all about how to send a simple HTTP GET request from Java program without using any third-party library. The HtppURLConnection is both powerful and easy but I don't recommend it to use in real-world production project because we have a better alternative in terms of Apache HttpClient library. If you haven't heard about it before, I suggest you look into that as it's an important library for Java developers.

Other Java Articles you may like
The Complete Java Master Class for Beginners

Thanks for reading this article so far. If you like this tutorial then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

How

2 comments:

  1. Follwing is the error when I used the same code "java.net.ConnectException: Connection refused: connect"

    ReplyDelete
  2. java.net.ConnectException: Connection refused: connect

    ReplyDelete