How to send HTTP POST request with Java without using any external libraries

I need to create a Java solution that will be able to send some bulk processing information back to a HTTP server endpoint. The Java solution should be as lean as possible, using as many facilities that Java provides out of the box. Luckily for me, Java do provides the java.net.HttpURLConnection class for me to build my solution. This post details a proof of concept which I did to get to know more about the java.net.HttpURLConnection class.

In this proof of concept, I create a Java console program that will hit the php endpoint which I had created earlier to proof that I can use jQuery to push a dynamically generated file to the web browser based on the user’s input.

Defining the server endpoint with the java.net.URL class

I first create an instance of the java.net.URL class, passing it the url of the server endpoint which will process my HTTP request.

URL serverUrl = 
    new URL("https://www.techcoil.com/process/proof-of-concepts/userNameAndLuckyNumberTextFileGeneration");

Getting an instance of java.net.HttpURLConnection object to send a HTTP request to the server and receive a HTTP response from the server

After I had defined the server endpoint to send my HTTP request, I call the open method of the URL object:

HttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();

I can then use the HttpURLConnection facilities via urlConnection to send the HTTP request to my server endpoint and read the HTTP response from it.

Preparing the HTTP request to send to the server endpoint

Once I have the HttpURLConnection object, I can write the following codes to construct the HTTP request to send to the server endpoint:

// Indicate that we want to write to the HTTP request body
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");

// Writing the post data to the HTTP request body
BufferedWriter httpRequestBodyWriter = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
httpRequestBodyWriter.write("visitorName=Johnny+Jacobs&luckyNumber=1234");
httpRequestBodyWriter.close();

By default, the HttpURLConnection object does not allow me to write to the HTTP request body. As such, I first configure the HttpURLConnection object to allow me to write to the HTTP request body by calling urlConnection.setDoOutput(true). I then call urlConnection.setRequestMethod("POST") to indicate the request method as HTTP post.

After I had configured the HttpURLConnection object, I layered the output stream to a java.io.BufferedWriter object. This allows me to write an encoded string to the HTTP request body. The encoded string sets "Johnny Jacobs" to the visitorName post variable and "1234" to the luckyNumber post variable.

Reading from the HTTP response from the server endpoint

The HTTP request will be sent to the server endpoint when my code starts to read from urlConnection. To read the HTTP response from the server endpoint, I wrote the following codes:

// Reading from the HTTP response body
Scanner httpResponseScanner = new Scanner(urlConnection.getInputStream());
while(httpResponseScanner.hasNextLine()) {
	System.out.println(httpResponseScanner.nextLine());
}
httpResponseScanner.close();

I layered the input stream of urlConnection to a java.util.Scanner object. This allows me to read the HTTP response body that the server sends back to me. I then use the Scanner object to read the response body and write to console, line by line.

A simple console application that sends a HTTP POST request to a server endpoint at Techcoil

The following sums up the points that are mentioned in this post:

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;


public class Program {

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

    // Define the server endpoint to send the HTTP request to
	URL serverUrl = 
    new URL("https://www.techcoil.com/process/proof-of-concepts/userNameAndLuckyNumberTextFileGeneration");
	HttpURLConnection urlConnection = (HttpURLConnection)serverUrl.openConnection();

	// Indicate that we want to write to the HTTP request body
	urlConnection.setDoOutput(true);
	urlConnection.setRequestMethod("POST");

	// Writing the post data to the HTTP request body
	BufferedWriter httpRequestBodyWriter = 
            new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
	httpRequestBodyWriter.write("visitorName=Johnny+Jacobs&luckyNumber=1234");
	httpRequestBodyWriter.close();

	// Reading from the HTTP response body
	Scanner httpResponseScanner = new Scanner(urlConnection.getInputStream());
	while(httpResponseScanner.hasNextLine()) {
		System.out.println(httpResponseScanner.nextLine());
	}
	httpResponseScanner.close();

    }
}

Any instances of java.io.IOException will be shown in the console screen. With that, I concluded my proof of concept of sending a HTTP POST request to a server endpoint with the facilities that Java provides me with.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.