Tuesday, October 4, 2011

HTTP POST in Java using URLConnection

 /*URLPost.java*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;


/**
 *
 * @author dhanoopbhaskar
 */
public class URLPost {


    public URLPost() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            /**
             * Constructing the data to be sent.
             * The data is encoded in UTF8 encoding scheme.
             * For that encode() method in the class java.net.URLEncoder 
             * is used
             */
            String data = URLEncoder.encode("sName", "UTF-8") + "=" + 
                    URLEncoder.encode("PI", "UTF-8");
            data += "&" + URLEncoder.encode("sData", "UTF-8") + "=" + 
                    URLEncoder.encode("3.14159", "UTF-8");
            System.out.println("Data: " + data);
            /**
             * URL to which the post data has to be sent.
             */
            URL url = new URL("http://localhost/cybman/test/post2.php");
            /**
             * A URLConnection is opened
             */
            URLConnection conn = url.openConnection();
            /**
             * The variable doOutput in URLConnection is false by default.
             * It should be set as true, otherwise we cannot write to a
             * URLConnection.
             * 
             * Possible Exception (if doOuput is false):
             * java.net.ProtocolException: cannot write to a URLConnection 
             * if doOutput=false - call setDoOutput(true)
             * at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(
             *                                      HttpURLConnection.java:885)
             *              
             */
            conn.setDoOutput(true);
            /**
             * Getting the output stream of URLConnection
             */
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                                                    conn.getOutputStream());
            /**
             * Writing and flushing the data
             */
            outputStreamWriter.write(data);
            outputStreamWriter.flush();
            /**
             * Getting the input stream of URLConnection
             */
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            System.out.print("Result: ");
            /**
             * The Response is read and displayed.
             */
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
            /**
             * Close the opened readers and writers.
             */
            outputStreamWriter.close();
            bufferedReader.close();
        } catch (MalformedURLException ex) { //thrown by new URL()
            System.out.println(ex);
        } catch (UnsupportedEncodingException ex) {
            //thrown by URLEncoder.encode()
            System.out.println(ex);
        } catch (IOException ex) { //thrown by stream class methods
            System.out.println(ex);
        } 
    }
}




OUTPUT
Data: sName=PI&sData=3.14159
Result: Done!!



/*post2.php*/


<?php
if(isset($_POST['sName']) && isset($_POST['sData'])) {
# Read the POST variables
$name = $_POST['sName'];
$data = $_POST['sData'];


# Create output string
$str = "\"$name\", \"$data\"\n";
 
# Open and write to file
$fh = fopen("postData.txt", "a+");
fwrite($fh, $str);
fclose($fh);
 
echo "Done!!";
}
?>




/*postData.txt*/

"PI", "3.14159"


0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

The Insane Techie - Android App

Launched an android app for the blog on 07th June 2016. Get it from google play store... Tips for using the app Use in landscape mo...