How to send a POST request using pure Java

In this tutorial we are going to show you how easy it is to send a POST request to a server using pure Java, no Apache HTTPClient is needed ;) We are using only java.net.* classes for this task.

Our sample POSTSenderExample class sends a POST request to http://echo.itcuties.com address which processes only POST requests. Here it is.

Java send POST request – POSTSenderExample class

package com.itcuties.java.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;
import java.net.URLEncoder;

/**
 * This is an example class that shows how to send a POST request
 * using pure JAVA.
 * 
 * @author itcuties
 *
 */
public class POSTSenderExample {

	/**
	 * Send a POST request to itcuties.com
	 * @param query
	 * @throws IOException 
	 */
	public String echoCuties(String query) throws IOException {
		// Encode the query 
		String encodedQuery = URLEncoder.encode(query, "UTF-8");
		// This is the data that is going to be send to itcuties.com via POST request
		// 'e' parameter contains data to echo
		String postData = "e=" + encodedQuery;
		
		// Connect to google.com
		URL url = new URL("http://echo.itcuties.com");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("Content-Length",  String.valueOf(postData.length()));
		
		// Write data
		OutputStream os = connection.getOutputStream();
		os.write(postData.getBytes());
		
		// Read response
		StringBuilder responseSB = new StringBuilder();
		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         
        String line;
        while ( (line = br.readLine()) != null)
        	responseSB.append(line);
				
		// Close streams
		br.close();
		os.close();
		
		return responseSB.toString();
		
	}
	
	// Run this example
	public static void main(String[] args) {
		try {
			
			System.out.println(new POSTSenderExample().echoCuties("Hi there!"));
			
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
}

At the beginning of this code we encode the data which we send to the server. URLEncoder.encode method is used for that. Next POST data is created – the e parameter is concatenated with the encoded query. Our server processes only the e parameter send via POST request. Next the HttpURLConnection object is created from the URL object. We set the request method to POST and two request properties, Content-Type and Content-Length, within the connection object. Next, all we do is obtaining the OutputStream object from the connection object and writing data bytes to it. Next, to read the response, we obtain the InputStream object from the connection object, and read it.

Download this sample code here.

This code is available on our GitHub repository as well.

3 Responses to "How to send a POST request using pure Java"

  1. Joeri says:

    Thanks for this tutorial man! Really helped me out!

    Reply
  2. Kumar says:

    I have a unique issue. I have to send JSON payload to Google Speech REST API. As per the API I have to send a GET type parameter at the end of the URL i.e. ‘?key=’

    Along with this I have to send JSON data as POST data as well. When I use a POST request and URL parameter is also going as part of the JSON body which is not as per the REST API interface. Is there someway I could achieve it using HttpUrlConnection.

    Reply
  3. kirubha says:

    Hi,
    How to set form parameters in this request?

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>