Sandeep is a ITA at Tata Consultancy Services. He also is the author of java blog. Sandeep has posted 24 posts at DZone. You can read more from them at their website. View Full User Profile

How To Send HTTP Post Request in Java

05.04.2011
| 25700 views |
  • submit to reddit

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

Published at DZone with permission of its author, Sandeep Bhandari.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Jilles Van Gurp replied on Thu, 2011/05/05 - 1:50am

I'd say, using raw java.io for this is somewhat of an antipattern. A few mistakes in your code:

1) your close is not in a finally block. Ok here because your application exits right away but you wouldn't be the first to be the rootcause of a server running out of file handles or connections in the pool because of such a basic mistake. Simple rule: if you have to close or release some resource, you have to do it in a finally block.

2) You are not setting any headers. Probably you want to be setting accept headers and content encoding headers (though you don't seem to have any).

3) You have a space in your url and are not handling the MalformedURLException

Use apache httpclient 4.x or one of the other frameworks (e.g. Jetty has a nice one). You'll be better off in terms of connection pooling, performance, resource management, robustness, etc. And it will be less lines of code as well.


 

Maheshkumar Per... replied on Thu, 2011/05/05 - 4:21am

Yes, I go with Jilles van Gurp. Sandeep, You can use HttpClient 4.x instead of reinventing the wheel. It provides lot more features and flexibility.

See also,

http://hc.apache.org/httpcomponents-client-ga/

Nicolas Frankel replied on Thu, 2011/05/05 - 4:58am

+1 for Jilles as well

darryl west replied on Thu, 2011/05/05 - 10:13am

One more +1 for the response from Jilles and +1 for apache http components from Maheshkumar. Even easier is to implement this using groovy.

Igor Polevoy replied on Sat, 2011/05/07 - 12:49am

+ 1 for Jilles; You also can check out this little library:

http://igorpolevoy.blogspot.com/2011/01/java-rest-with-ease.html

Makes it trivial to build REST HTTP clients.

cheers,

igor

 

 

Sandeep Bhandari replied on Sat, 2011/05/07 - 2:04pm

Thanks for suggesting these tools guys.

But the code I have written was meant to test REST web service and wanted not to spend time on searching and learning to use all those tools mentioned by you guys.

Extreme Java

 

 

Maheshkumar Per... replied on Tue, 2011/05/24 - 9:44pm in response to: Sandeep Bhandari

Normal 0 false false false MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}

Do you think that spending time on searching and learning is waste? Then how did you learn JAVA? Will you write or paste the same code in all projects?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.