Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How To Send HTTP Post Request in Java

DZone's Guide to

How To Send HTTP Post Request in Java

· Java Zone
Free Resource

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}