Java HTTP GET/POST Request Example Tutorial

This tutorial shows how to send a GET and a POST request in Java. We use built-in HttpURLConnection class and Apache HttpClient class.

HTTP

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.

HTTP GET

The HTTP GET method requests a representation of the specified resource. Requests using GET should only retrieve data.

HTTP POST

The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.

Java HTTP GET Request with HttpURLConnection

In this example, we use HttpURLConnection class to send an HTTP GET request to Google.com to get the search result:
package net.javaguides.network;

import java.io.BufferedReader;

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

public class HttpURLConnectionExample {

    private static final String USER_AGENT = "Mozilla/5.0";

    private static final String GET_URL = "https://www.google.com/search?q=javaguides";

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

    private static void sendHttpGETRequest() throws IOException {
        URL obj = new URL(GET_URL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = httpURLConnection.getResponseCode();
        System.out.println("GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in .readLine()) != null) {
                response.append(inputLine);
            } in .close();

            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("GET request not worked");
        }

        for (int i = 1; i <= 8; i++) {
            System.out.println(httpURLConnection.getHeaderFieldKey(i) + " = " + httpURLConnection.getHeaderField(i));
        }

    }
}
Output:
GET Response Code :: 200
Google search result ....
Date = Tue, 14 May 2019 08:50:16 GMT
Expires = -1
Cache-Control = private, max-age=0
Content-Type = text/html; charset=UTF-8
P3P = CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server = gws
X-XSS-Protection = 0
X-Frame-Options = SAMEORIGIN

Java HTTP POST Request with HttpURLConnection

In this example, we use HttpURLConnection class to send an HTTP POST request to http://localhost:8080/login-jsp-jdbc-mysql-example/login.jsp link.
To test POST HTTP request, I am using a sample project from login-jsp-jdbc-mysql-tutorial because it has a login form with POST HTTP method. I have deployed it on my localhost tomcat server.
Here is a complete Java program to send Http Post request:
package net.javaguides.network;

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

public class HttpURLConnectionExample {

    private static final String USER_AGENT = "Mozilla/5.0";

    private static final String POST_URL = "http://localhost:8080/login-jsp-jdbc-mysql-example/login.jsp";

    private static final String POST_PARAMS = "userName=Ramesh&password=Pass@123";

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

        sendPOST();
    }

    private static void sendPOST() throws IOException {
        URL obj = new URL(POST_URL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) obj.openConnection();
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("User-Agent", USER_AGENT);

        // For POST only - START
        httpURLConnection.setDoOutput(true);
        OutputStream os = httpURLConnection.getOutputStream();
        os.write(POST_PARAMS.getBytes());
        os.flush();
        os.close();
        // For POST only - END

        int responseCode = httpURLConnection.getResponseCode();
        System.out.println("POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in .readLine()) != null) {
                response.append(inputLine);
            } in .close();

            // print result
            System.out.println(response.toString());
        } else {
            System.out.println("POST request not worked");
        }
    }
}
Note: If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. Rest all the steps will be the same as above, HttpsURLConnection will take care of SSL handshake and encryption.

Using the Apache HttpClient - Add Dependency

The Apache HttpClient library allows handling HTTP requests. To use this library add a dependency to your Maven or Gradle build file. You find the latest version here: https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
We use maven to manage our dependencies and are using Apache HttpClient version 4.5. Add the following dependency to your project in order to make HTTP GET/POST request method.
<dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpclient</artifactId>
     <version>4.5</version>
</dependency>

Java HTTP GET Request with Apache HTTPClient

In the following example, we retrieve a resource from http://httpbin.org/get. This resource returns a JSON object which we’ll simply print to the console. In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.
package com.javadevelopersguide.httpclient.examples;

import org.apache.http.HttpEntity;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

/**
 * This example demonstrates the use of {@link HttpGet} request method.
 * @author Ramesh Fadatare
 */
public class HttpGetRequestMethodExample {

    public static void main(String...args) throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            //HTTP GET method
            HttpGet httpget = new HttpGet("http://httpbin.org/get");
            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}
Output:
Executing request GET http://httpbin.org/get HTTP/1.1
----------------------------------------
{
  "args": {}, 
  "headers": {
    "Accept-Encoding": "gzip,deflate", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "Apache-HttpClient/4.5 (Java/1.8.0_172)"
  }, 
  "origin": "49.35.12.218", 
  "url": "http://httpbin.org/get"
}

Java HTTP POST Request with Apache HTTPClient

Let's discuss how to use HttpClient in real-time projects. Consider we have deployed Spring boot Restful CRUD APIs. Check out this article - Spring Boot 2 + hibernate 5 + CRUD REST API Tutorial.
In the following example, we send a resource to http://localhost:8080/api/v1/users. This resource accepts the request JSON, process it and store it into a database. This service also returns a response with a resource. In this example, we are using Java 7 try-with-resources to automatically handle the closing of the ClosableHttpClient and we are also using Java 8 lambdas for the ResponseHandler.
package com.javadevelopersguide.httpclient.examples;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * This example demonstrates the use of {@link HttpPost} request method.
 * @author Ramesh Fadatare
 */
public class HttpPostRequestMethodExample {

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

    public static void postUser() throws IOException {
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost("http://localhost:8080/api/v1/users");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            String json = "{\r\n" +
                "  \"firstName\": \"Ram\",\r\n" +
                "  \"lastName\": \"Jadhav\",\r\n" +
                "  \"emailId\": \"[email protected]\",\r\n" +
                "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" +
                "  \"createdBy\": \"Ramesh\",\r\n" +
                "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" +
                "  \"updatedby\": \"Ramesh\"\r\n" +
                "}";
            StringEntity stringEntity = new StringEntity(json);
            httpPost.setEntity(stringEntity);

            System.out.println("Executing request " + httpPost.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response - > {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            };
            String responseBody = httpclient.execute(httpPost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        }
    }
}

Output

Executing request POST http://localhost:8080/api/v1/users HTTP/1.1
----------------------------------------
{"id":37,"firstName":"Ram","lastName":"Jadhav","emailId":"[email protected]",
"createdAt":"2018-10-29T09:37:09.821+0000","createdBy":"Ramesh","updatedAt":"2018-10-29T09:37:09.821+0000",
"updatedby":"Ramesh"}

Conclusion

In this tutorial, we have seen how to send a GET and a POST request in Java. We have used built-in HttpURLConnection class and Apache HttpClient class to send GET/POST request in Java.
Check out complete apache HTTPClient library tutorial at https://www.javaguides.net/p/apache-httpclient-tutorial.html.

Reference

Comments