2011-06-29

利用 Java 發送 HTTP POST 請求 (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");
此例子顯示 args 是一組連續參數像
可以利用此功能連續自動發送 HTTP 往目的地
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.

沒有留言 :

張貼留言