0

This is my java code to send data through HTTPPost request:

import java.io.*;
import java.net.*;
class HttpURLConnectionEx{
    public static void main(String[] args) throws Exception{    
    URL targetURL = new URL("http://localhost/JAVA/post.php");
    HttpURLConnection conn =(HttpURLConnection) targetURL.openConnection();
    String body= "fName="+ URLEncoder.encode("value1","UTF-8")+"&lName=" + URLEncoder.encode("value2","UTF-8");
    conn.setDoOutput(true);
    conn.setInstanceFollowRedirects(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("charset", "UTF-8");
    conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
    try
    {
     OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
     out.write(body);

      // Get the response
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while((line = rd.readLine()) != null) {
           System.out.println(line);
      }
      }catch(Exception e){
        e.printStackTrace();
      } 
   }
}

This is my PHP code present in localhost:

<?php
    $data = $_POST["fName"];
    $dbc = mysqli_connect('localhost','root','root123','JAVA')
           or die("error connecting to mysql server");
    $query = "INSERT INTO insert_table(data) VALUES('".$data."')";
    if($query){
        echo "data inserted sucessfully";
    }
    $result = mysqli_query($dbc,$query) or die("error querying database");
?>

This is the output i 'm getting when i run it in commandline: enter image description here

1 Answer 1

0

A flush after the write is required.

 out.flush();

edit

Undefined index: fName

The php error is clear enough, isn't? The $_POST array doesn't contain your POST variables.

First I've checked on php side the content of the post with var_dump($_POST) and:

/* save the raw post to a file */
file_put_contents('/tmp/post.txt', file_get_contents('php://input'));

Both were empty, so I used wireshark to check the HTTP/POST content, it was done but with Content-Length: 0 and without body.

Few googles to something similar to your code and I noticed the flush that mean OutputStreamWriter is buffered and at the time of the post request the output could be not written (sent to the server) or only partially, a good reason for zero content-length.

At this point I think you don't need to use conn.setRequestProperty for "Content-Length", it should be updated according with your buffer content length.

1
  • I tried out.close() which is also working fine.But i didn't get how above notice removed,by using out.close()/out.flush(). I want to know reason behind using out.close()/out.flush() which removed notice in output. Commented Sep 29, 2013 at 12:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.