8.3.09

Sending HTTP Posts through JAVA

I found this truly helpful tip :D

http://www.javaworld.com/javatips/jw-javatip34.html?page=1

From the site:

    URL              url;
    URLConnection   urlConn;
    DataOutputStream    printout;
    DataInputStream     input;
    // URL of CGI-Bin script.
    url = new URL (getCodeBase().toString() + "env.tcgi");
    // URL connection channel.
    urlConn = url.openConnection();
    // Let the run-time system (RTS) know that we want input.
    urlConn.setDoInput (true);
    // Let the RTS know that we want to do output.
    urlConn.setDoOutput (true);
    // No caching, we want the real thing.
    urlConn.setUseCaches (false);
    // Specify the content type.
    urlConn.setRequestProperty
    ("Content-Type", "application/x-www-form-urlencoded");
    // Send POST output.
    printout = new DataOutputStream (urlConn.getOutputStream ());
    String content =
    "name=" + URLEncoder.encode ("Buford Early") +
    "&email=" + URLEncoder.encode ("buford@known-space.com");
    printout.writeBytes (content);
    printout.flush ();
    printout.close ();
    // Get response data.
    input = new DataInputStream (urlConn.getInputStream ());
    String str;
    while (null != ((str = input.readLine())))
    {
    System.out.println (str);
    textArea.appendText (str + "\n");
    }
    input.close ();



Thanks to the person who posted this :D