How to build a HTTP POST Request with Java?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    How to build a HTTP POST Request with Java?

    Hi everybody.

    After years of C# and PHP, I'm finally returning to Java.
    My goal is to create a Java program capable of sending images to a PHP Photo Album on my web server.

    Right now, however, I am stuck trying to send simple text variables through POST to my PHP script.
    The code does seem to connect to the script like it is supposed to, but it seems unable to send the POST variables. The PHP script is returning a 'Undefined index' warning for the variables, like they don't exists.

    My Java Code:
    [code=java]
    public static void main(String[] args) {
    try {
    URL url;
    URLConnection urlConnection;
    DataOutputStrea m outStream;
    DataInputStream inStream;

    // Build request body
    String body =
    "fName=" + URLEncoder.enco de("Atli", "UTF-8") +
    "&lName=" + URLEncoder.enco de("Þór", "UTF-8");

    // Create connection
    url = new URL("http://192.168.1.68/test/POST/post.php");
    urlConnection = url.openConnect ion();
    ((HttpURLConnec tion)urlConnect ion).setRequest Method("POST");
    urlConnection.s etDoInput(true) ;
    urlConnection.s etDoOutput(true );
    urlConnection.s etUseCaches(fal se);
    urlConnection.s etRequestProper ty("Content-Type", "applicatio n/x-www-form-urlencoded");
    urlConnection.s etRequestProper ty("Content-Length", ""+ body.length());

    // Create I/O streams
    outStream = new DataOutputStrea m(urlConnection .getOutputStrea m());
    inStream = new DataInputStream (urlConnection. getInputStream( ));

    // Send request
    outStream.write Bytes(body);
    outStream.flush ();
    outStream.close ();

    // Get Response
    // - For debugging purposes only!
    String buffer;
    while((buffer = inStream.readLi ne()) != null) {
    System.out.prin tln(buffer);
    }

    // Close I/O streams
    inStream.close( );
    outStream.close ();
    }
    catch(Exception ex) {
    System.out.prin tln("Exception cought:\n"+ ex.toString());
    }
    }
    [/code]

    And the PHP code:
    [code=php]
    <?php
    # Read GET variables
    $fName = $_POST['fName'];
    $lName = $_POST['lName'];

    # Create output string
    $str = "\"$fName\" , \"$lName\"\n ";

    # Open and write to file
    $fh = fopen("postData .txt", "a+");
    fwrite($fh, $str);
    fclose($fh);

    echo "done";
    ?>
    [/code]

    Any thoughts?
    Thanks.
  • ak1dnar
    Recognized Expert Top Contributor
    • Jan 2007
    • 1584

    #2
    Some where from the internet:

    [CODE=java]
    import java.io.Buffere dReader;
    import java.io.InputSt reamReader;
    import java.io.OutputS treamWriter;
    import java.net.URL;
    import java.net.URLCon nection;
    import java.net.URLEnc oder;

    public class POSTDATA {


    public POSTDATA() {
    }
    public static void main(String[] args) {
    try {
    // Construct data
    String data = URLEncoder.enco de("fName", "UTF-8") + "=" + URLEncoder.enco de("value1", "UTF-8");
    data += "&" + URLEncoder.enco de("lName", "UTF-8") + "=" + URLEncoder.enco de("value2", "UTF-8");

    // Send data
    URL url = new URL("http://localhost/TUT/POSTDATA/post.php");
    URLConnection conn = url.openConnect ion();
    conn.setDoOutpu t(true);
    OutputStreamWri ter wr = new OutputStreamWri ter(conn.getOut putStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader( new InputStreamRead er(conn.getInpu tStream()));
    String line;
    while ((line = rd.readLine()) != null) {
    System.out.prin tln(line);
    }
    wr.close();
    rd.close();
    } catch (Exception e) {
    }
    }

    }


    [/CODE]

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      #3
      Thank you for that!

      After comparing my code to yours I realized that my mistake was to call the 'urlConnection. getInputStream( )' method (line 25) before I sent the request. It appears to send the request when this method is called, ignoring any future changes to it.

      Thanks again, ajaxrand.

      Comment

      • ak1dnar
        Recognized Expert Top Contributor
        • Jan 2007
        • 1584

        #4
        Welcome. And this also will helpul Atli.

        Originally posted by java documentaion 1.5.0
        java.io.DataInp utStream.readLi ne()
        This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader. readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
        [CODE=java] DataInputStream d = new DataInputStream (in);[/CODE]
        with:
        [CODE=java] BufferedReader d
        = new BufferedReader( new InputStreamRead er(in));
        [/CODE]

        Comment

        • freddieMaize
          New Member
          • Aug 2008
          • 85

          #5
          May I cont. this thread?

          May I cont.with this old thread?

          Below is my login jsp page]
          Code:
              <form action="success.jsp" method="POST">
              <input type="text" name="fname" value="" />
              <input type="text" name="lname" value="" />
          Below is my success jsp page
          Code:
                  
                  out.println("first name "+request.getParameter("fname"));
                  out.println("last name "+request.getParameter("lname"));
          if (request.getParameter("fname").equalsIgnoreCase("freddie")&&request.getParameter("lname").equalsIgnoreCase("maize")){
                    out.println("Successful Login");
                  }
                  else{
                    out.println("Login failed");
                  }
          When I try to login using my Java POST method (using the code that is posted above) I'm getting login failed. Below is how it looks like,

          Code:
          <html>
              <head>
                  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                  <title>JSP Page</title>
              </head>
              <body>       
                  <h2>Hello World!</h2>
                  first name freddielname=maize
          last name null
          Login failed
              </body>
          </html>
          If you see the first out.print(), i'm getting both the fname and lname there which should not be. How do i deal this? Thanks

          fREDDIE

          Comment

          • freddieMaize
            New Member
            • Aug 2008
            • 85

            #6
            Originally posted by freddieMaize
            May I cont.with this old thread?

            Below is my login jsp page]
            Code:
                <form action="success.jsp" method="POST">
                <input type="text" name="fname" value="" />
                <input type="text" name="lname" value="" />
            Below is my success jsp page
            Code:
                    
                    out.println("first name "+request.getParameter("fname"));
                    out.println("last name "+request.getParameter("lname"));
            if (request.getParameter("fname").equalsIgnoreCase("freddie")&&request.getParameter("lname").equalsIgnoreCase("maize")){
                      out.println("Successful Login");
                    }
                    else{
                      out.println("Login failed");
                    }
            When I try to login using my Java POST method (using the code that is posted above) I'm getting login failed. Below is how it looks like,

            Code:
            <html>
                <head>
                    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                    <title>JSP Page</title>
                </head>
                <body>       
                    <h2>Hello World!</h2>
                    first name freddielname=maize
            last name null
            Login failed
                </body>
            </html>
            If you see the first out.print(), i'm getting both the fname and lname there which should not be. How do i deal this? Thanks

            fREDDIE
            Resolved. Used below,
            Code:
                    String body = 
                    "fName=" + URLEncoder.encode("Atli", "UTF-8") + 
                    "&lName=" + URLEncoder.encode("Þór", "UTF-8");
            instead of below
            Code:
             String data = URLEncoder.encode("fName", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); 
                    data += "&" + URLEncoder.encode("lName", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8")
            Thanks

            Comment

            Working...