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
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
     * 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);

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


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