Java HttpURLConnection Class Example – Java HTTP Request GET, POST

HttpURLConnection class from java.net package can be used to send Java HTTP Request programmatically. In this post, we will learn how to use HttpURLConnection in java program to send GET and POST requests and then print the response.

HttpURLConnection Class - Java HTTP GET Request Example

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

HttpURLConnection Class - Java HTTP POST Request Example

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.

Comments