How to Send HTTP Request from a 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 the java.net package to send a simple HTTP request in Java. But, first, let me answer your first question, is it possible to send an HTTP request in Java? Yes, it's possible and you can send any kind of HTTP request like 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.

Btw, if If you are a beginner and want to learn Java from Scratch, I suggest you check out The Complete Java MasterClass course, the most comprehensive and up-to-date course, which is recently updated for Java 11 as well





Simple HTTP Client in Java - HttpURLConection Example

Without wasting any more of your time, here is our Java program to connect to a server and send HTTP requests. It's like a simple HTTP client built using core Java and without using any third-party library like Apache HttpClient or Spring Framework. 

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 the program is really simple and if you look at the import we have used just a couple of classes like 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 Tutorials and Resources you may like
  • 7 Best Courses to learn Spring Framework (best courses)
  • Top 5 Books to learn RESTful APIs and Web Services (books)
  • How to create a REST client using the Spring framework in Java? (tutorial)
  • 10 Free Courses to learn Spring Boot (Free Courses)
  • Spring HelloWorld Example using Dependency Injection (tutorial)
  • The difference between PUT vs POST in REST Web Service? (article)
  • Top 5 courses to learn GraphQL for Beginners (courses)
  • The difference between REST and SOAP Web Services? (answer)
  • Top 10 REST Web Service Interview Questions (answer)
  • Top 5 Courses to learn RESTFul Web Services in Java? (courses)
  • The difference between Idempotent and safe methods in HTTP? (answer)
  • How to convert a JSON array to a String array in Java? (tutorial)
  • How to create a JDBC connection pool using Spring? (tutorial)
  • My Favorite Courses to learn Software Architecture (courses)
  • Top 10 Courses to learn Microservices for Java developers (courses)

Thanks for reading this article so far. If you like this tutorial of sending HTTP requests from the Java Program then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are new to the Java world and looking for a free online course to learn Java in a step-by-step and structured way then you can also checkout this Java Tutorial for Complete Beginners(FREE)  course on Udemy. More than 1 million people have joined this course to learn Java and you can do so for FREE as well. 

3 comments:

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

    ReplyDelete
    Replies
    1. May be server would be down, check if server is up by using telenet host port command.

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

    ReplyDelete

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