Make HTTP request from a Java program

In this tutorial, we will learn how to make HTTP GET/POST request using a Java program with the help of some easy-to-understand examples. As you know, the world nowadays revolves around the Internet. You might get into a situation where you need to access a website to send/receive data directly from your Java program. This tutorial will help you prepare for such situations.

We will learn how to make HTTP GET/POST request using a Java program in a modern way. There are many methods/APIs/built-in classes in Java available to do so. We will be using OkHttp client API in this tutorial.

So let us start!

HTTP Request from a Java Program

  1. Brief Introduction to OkHttp:
    • OkHttp is easy to implement HTTP/HTTP 2 client which can be used for both Android as well as Java applications.
    • It is equipped with great features like connection pooling(when HTTP 2 isn’t available), GZIP compression and response caching.
    • OkHttp works well with Android 5.0 and above. The minimum requirement for Java is Java 8 and above.
    • Learn more about it here: https://square.github.io/okhttp/
  2. Adding Maven Dependency:
    • Add the following code to your pom.xml file. We will be using OkHttp version 4.3.1 in this tutorial.
      <dependency>
          <groupId>com.squareup.okhttp3</groupId>
          <artifactId>okhttp</artifactId>
          <version>4.3.1</version>
      </dependency>
    • Now that everything is set up, let’s see how to implement HTTP GET/POST request one by one.
  3.  Synchronous GET Request with OkHttp:
    • For sending synchronous GET requests, we need to first implement an object of Request class, which will carry our request to the server from our Java program. It takes a URL as an argument. You can add request headers such as key, id, etc here as well.
      Request request = new Request.Builder()
                     .url("url")
                     .addHeader("custom-key", "id") //request headers
                     .build();

       

    • For receiving the response from the server, we need to first implement the request by calling the function newCall() of the class Call implicitly. Then we will pass its output to the object of the Response class to finally get a response from the server by calling its execute() function. Now the code will look as:
      Request request = new Request.Builder()
              .url("url")
              .addHeader("custom-key", "id") //request headers
              .build();
      
      try (Response response = httpClient.newCall(request).execute()) {
      
          if (!response.isSuccessful()) throw new IOException("Unknown code " + response);
      
          // Get response body
          System.out.println(response.body().string());
      }
  4.  POST Request with OkHttp:
    • Let’s see a simple POST request by building a RequestBody to pass the parameters such as username and password. It is a basic example but will help in understanding how we pass the form parameters to the POST request. Again we need to make an object of Request class to carry the request and an object of Response class to record the response of the server.
      // form parameters
              RequestBody formBody = new FormBody.Builder()
                      .add("username", "example")
                      .add("password", "example")
                      .build();
      
              Request request = new Request.Builder()
                      .url("url")
                      .addHeader("custom-key", "id")
                      .post(formBody)
                      .build();
      
              try (Response response = httpClient.newCall(request).execute()) {
      
                  if (!response.isSuccessful()) throw new IOException("Unknown code " + response);
      
                  // Get response body
                  System.out.println(response.body().string());
              }
      

       

  5.  Example:
    • Now that we have learned how to make the HTTP GET/POST request individually, we will combine them both into a single Java program to see the output. We will make a public class OkHttpExample having two functions:- sendGet() and sendPost() to send the GET/POST requests and record their responses respectively. We will be using a website called http://httpbin.org/which is a simple website to test various HTTP functions.
      package com.shan.HttpUsingJava.HttpJava;
      
      
      import okhttp3.*;
      
      import java.io.IOException;
      
      public class OkHttpExample {
      
          private final OkHttpClient httpClient = new OkHttpClient();
      
          public static void main(String[] args) throws Exception {
      
              OkHttpExample obj = new OkHttpExample();
      
              System.out.println(" Send Http GET request");
              obj.sendGet();
      
              System.out.println(" Send Http POST request");
              obj.sendPost();
      
          }
      
          private void sendGet() throws Exception {
      
              Request request = new Request.Builder()
                      .url("https://httpbin.org/get")
                      .addHeader("custom-key", "id") //request headers
                      .build();
      
              try (Response response = httpClient.newCall(request).execute()) {              if (!response.isSuccessful()) throw new IOException("Unknown code " + response);
      
                  // Get response body
                  System.out.println(response.body().string());
              }
      
          }
      
          private void sendPost() throws Exception {
      
              // form parameters
              RequestBody formBody = new FormBody.Builder()
                      .add("username", "example")
                      .add("password", "example")
                      .build();
      
              Request request = new Request.Builder()
                      .url("https://httpbin.org/post")
                      .addHeader("custom-key", "id")
                      .post(formBody)
                      .build();
      
              try (Response response = httpClient.newCall(request).execute()) {
      
                  if (!response.isSuccessful()) throw new IOException("Unknown code " + response);
      
                  // Get response body
                  System.out.println(response.body().string());
              }
      
          }
      
      }
      
      
  6. Output:
    • When you successfully run the code, you should get the following output:
       Send Http GET request
      {
        "args": {}, 
        "headers": {
          "Accept-Encoding": "gzip", 
          "Custom-Key": "id", 
          "Host": "httpbin.org", 
          "User-Agent": "okhttp/4.3.1", 
          "X-Amzn-Trace-Id": "Root=1-5e7efa7c-ec3b9cbe51cbfd0039150b70"
        }, 
        "origin": "27.62.214.110", 
        "url": "https://httpbin.org/get"
      }
      
       Send Http POST request
      {
        "args": {}, 
        "data": "", 
        "files": {}, 
        "form": {
          "password": "example", 
          "username": "example"
        }, 
        "headers": {
          "Accept-Encoding": "gzip", 
          "Content-Length": "33", 
          "Content-Type": "application/x-www-form-urlencoded", 
          "Custom-Key": "id", 
          "Host": "httpbin.org", 
          "User-Agent": "okhttp/4.3.1", 
          "X-Amzn-Trace-Id": "Root=1-5e7efa7c-cd9c5fca0abedac243af9a7a"
        }, 
        "json": null, 
        "origin": "27.62.214.110", 
        "url": "https://httpbin.org/post"
      }
      
      

       

  7. Conclusion:
    • I hope you understood how to send an HTTP request using a Java program. Happy Learning!

Also read: Generate PDF from HTML in Java

Leave a Reply

Your email address will not be published. Required fields are marked *