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* classes for this task.

Our sample POSTSenderExample class sends a POST request to address which processes only POST requests. Here it is.

Java send POST request – POSTSenderExample class



 * 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
	 * @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 via POST request
		// 'e' parameter contains data to echo
		String postData = "e=" + encodedQuery;
		// Connect to
		URL url = new URL("");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("Content-Length",  String.valueOf(postData.length()));
		// Write data
		OutputStream os = connection.getOutputStream();
		// Read response
		StringBuilder responseSB = new StringBuilder();
		BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ( (line = br.readLine()) != null)
		// Close streams
		return responseSB.toString();
	// Run this example
	public static void main(String[] args) {
		try {
			System.out.println(new POSTSenderExample().echoCuties("Hi there!"));
		} catch (IOException ioe) {

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.

One Response to "How to send a POST request using pure Java"

  1. Joeri says:

    Thanks for this tutorial man! Really helped me out!


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>