Jun 18, 2011

Using Java to send HTTP Request with POST method


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public static void sentHttpPostRequest(String url, String args) throws IOException {
    URLConnection connection = new URL(url).openConnection();
    // by default, connection with enable input, but won't enable output
    connection.setDoOutput(true);
    //connection.setDoInput(true);
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    out.write(args);
    out.flush();
    out.close();
    /*
     * If the page has respond, uncomment these statements the retrieve the respond data
    InputStream is = connection.getInputStream();
    FileOutputStream fos = new FileOutputStream("respond.txt");
    byte[] buffer = new byte[1024];
    for (int length; (length = is.read(buffer)) > 0;) {
        fos.write(buffer, 0, length);
    }
    fos.close();
    is.close();
    */
}

sentHttpPostRequest("http://somewhere/somefile", "arg1=value1&arg2=value2")

This example shows the args parameter is a chain of connected arguments.
You can perform an automatic task of HTTP request to the target site rapidly.
However, "Don't Be Evil" when you are using this method


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Google Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Hostgator Coupon Code