Java, Programming

Using Java to send HTTP Request with POST method

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 to 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 the HTTP request to the target site rapidly.

However, “Don’t Be Evil” when you are using this method