Java HTTP POST Request Example - HttpURLConnection

In this example, we use the HttpURLConnection class to send an HTTP POST request to http://localhost:8080/login-jsp-jdbc-mysql-example/login.jsp link.

HttpURLConnection Class - Java HTTP POST Request Example

To test the POST HTTP request, I am using a sample project from login-jsp-jdbc-mysql-tutorial because it has a login form with the 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