Saturday, August 15, 2009

java: Perform HTTP POST operation with URLConnection

Share at Facebook

Using the class URLConnection you can easily do your regular HTTP POST operation. Its almost similar to the GET operation. This case, you'll just need to write the post parameter to the post url. That's it. Here is an example code that will post some data to the post url, and the response HTML is at String html

String html = "";
String postUrl = "";
String data = "x=10&y=20";

URL url = new URL(postUrl);
URLConnection urlConnection = url.openConnection();

// Posting the content
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());

// make an input stream from the remote url
DataInputStream dis = new DataInputStream(urlConnection.getInputStream());
// read until all the html codes are fetched
String tmp;
while ((tmp = dis.readLine()) != null) {
html += tmp;

// close the shits

At above code, you can see that I have posted my content at the site using OutputStreamWriter. But don't forget to encode your post string before sending.

After posting the data, I have read the HTML from the site using DataInputStream from the connection. This is as like the GET method, just the OutputStreamWriter makes the different between the POST and GET method.

Hope you enjoyed this small piece of code.

No comments: