How do I send a POST request using Java?
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.
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");
No comments:
Post a Comment