A POST request can be used for multiple purposes on the web. It can be used for performing the Create or Update operations for various resources. The most common usage of a POST request is in the form of a FORM on an HTML page.
The HTTP protocol doesn’t say anything about the best way to use the POST request but with the web the HTML has become the standard for issuing POST request.
One can also send POST requests from javascript (AJAX), .Net, PHP or Java based programs. Recently I had written a program to issue a POST request in Java.
If you have server listening for requests then this program code can be handy. In my case, it was a REST web service which was listening for POST requests. One can also issue these HTTP requests for servlets too.
The code follows:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
public class PostExample { | |
public static void main(String[] args) throws IOException { | |
String urlParameters = "name=Hello"; | |
String request = "http://www.xyz.com"; | |
URL url = new URL(request); | |
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); | |
connection.setDoOutput(true); | |
connection.setDoInput(true); | |
connection.setInstanceFollowRedirects(false); | |
connection.setRequestMethod("POST"); | |
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); | |
connection.setRequestProperty("charset", "utf-8"); | |
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); | |
connection.setUseCaches(false); | |
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); | |
wr.writeBytes(urlParameters); | |
wr.flush(); | |
String line; | |
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); | |
while ((line = reader.readLine()) != null) { | |
System.out.println(line); | |
} | |
wr.close(); | |
reader.close(); | |
connection.disconnect(); | |
} | |
} |