Over a million developers have joined DZone.
Silver Partner

How To Send HTTP Post Request in Java

· Java Zone

The Java Zone is brought to you in partnership with JetBrains.  Learn about instant and clever code completion, on-the-fly code analysis and reliable refactoring tools with IntelliJ IDEA.

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:

package test;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test {
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost:8080/resttest/services/Order /3");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
out.close();
}
}

Please replace the URL with the actual URL where the server application is listening for POST requests.

One can also use the same code for issuing the other HTTP requests which are GET,PUT and DELETE. To achieve that, change the line:

httpCon.setRequestMethod("POST");

to

httpCon.setRequestMethod("GET");
httpCon.setRequestMethod("PUT");
httpCon.setRequestMethod("DELETE");

From  http://extreme-java.blogspot.com/2011/04/how-to-send-http-post-request-in-java.html

The Java Zone is brought to you in partnership with JetBrains.  Learn about instant and clever code completion, on-the-fly code analysis and reliable refactoring tools with IntelliJ IDEA.

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}