-1

I implemented android code to send JSON string to the server. I am getting this json string '{"mac": "23:A5:J0:06:C6:E9", "latitude":84.16898451,"longitude":3.16561387,"route": 1}' as output in the doInBackground method and am getting the output The output of getResponsecode: The output of getResponsecode: 200 in the client side.

I checked my php file in the localhost and when I fresh the index.php homepage, the bus table is being created and data updated if I change some values in the JSON string. I could not connect my S4 device to the localhost directly to check it since I am using public hotspot.

I have uploaded the index.php file the online file manager in htdocs directory on byethost.com server, the table bus is being created but no record is being inserted and then updated.

Is it possible with HttpURLConnection to check whether the data has been inserted/updated successfully in the bus table? Should I add another path for first parameter of the file_get_contents method else php://input?

doInBackground method:

protected Void doInBackground(String... params) {
    // TODO Auto-generated method stub

    try {
        System.out.println("The output of : doInBackground " +params[0]);

        URL myUrl = new URL("http://username.byethost8.com/index.php");
        HttpURLConnection conn = (HttpURLConnection) myUrl
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setRequestProperty("Content-Type",
                "application/json");
        conn.connect();
        System.out.println("The output of getResponsecode: "+conn.getResponseCode());
        // create data output stream
        DataOutputStream wr = new DataOutputStream(
                conn.getOutputStream());
        // write to the output stream from the string
        wr.writeBytes(params[0]);
        wr.close();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;

}

index.php:

    <?php
     $json = json_decode ( file_get_contents ( 'php://input', true ) );
     $con = new mysqli ( "domain.com", "user_name", "password", "database_name" );
    // I tried with this string to test the index.php file and everything works
// $json = '{"mac": "23:A5:J0:06:C6:E9", "latitude":84.16898451,"longitude":3.16561387,"route": 1}';

    $data = json_decode ( $json );

    $mac = $data->{'mac'};
    $latitude = $data->{'latitude'};
    $longitude = $data->{'longitude'};
    $route =   $data->{'route'};


    require 'connection.php';

    // check whether route's table exist.
    $results = $con->query ( "SHOW TABLES like 'bus' " ) or die ( mysqli_error () );

    if (($results->num_rows) == 1) {
      //"UPDATE MyGuests SET lastname='Doe' WHERE id=2"
     $sql = "REPLACE INTO bus(mac, route, latitude, longitude)
              VALUES( ?, ?, ? , ? )";
      $stmt = $con->prepare($sql) or die ( $con->error );
      $stmt->bind_param("ssss",$mac,$route, $latitude,$longitude);
      $stmt->execute();

      $stmt->close();

      echo "Table exist";
    } else {
      $create =  "CREATE TABLE bus
           (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
            mac VARCHAR(30) NOT NULL UNIQUE,
            route int(11) NOT NULL,
         latitude FLOAT(10,6) NOT NULL , 
         longitude FLOAT(10,6) NOT NULL,
         created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)" ;
       $stmt = $con->prepare($create) or die ( $con->error );
      $stmt->execute();

      $stmt->close();

      echo "table was created";
    }

some of the Logcat output:

04-29 22:18:28.541: W/System.err(32348): java.net.ProtocolException: cannot write request body after response has been read
04-29 22:18:28.541: W/System.err(32348):  at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:214)
04-29 22:18:28.551: W/System.err(32348):  at com.bustracker.MyAsyncTask.doInBackground(PostData.java:61)
04-29 22:18:28.551: W/System.err(32348):  at com.bustracker.MyAsyncTask.doInBackground(PostData.java:1)
04-29 22:18:28.551: W/System.err(32348):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-29 22:18:28.551: W/System.err(32348):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-29 22:18:28.551: W/System.err(32348):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-29 22:18:28.551: W/System.err(32348):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-29 22:18:28.551: W/System.err(32348):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-29 22:18:28.551: W/System.err(32348):  at java.lang.Thread.run(Thread.java:818)
04-29 22:18:28.561: I/System.out(32348): The output of : doInBackground {"mac":"89:GG:D0:06:86:M6","latitude":93.86900553,"longitude":25.66558334,"route":4}
04-29 22:18:28.591: I/System.out(32348): (HTTPLog)-Static: isSBSettingEnabled false
04-29 22:18:28.591: I/System.out(32348): KnoxVpnUidStorageknoxVpnSupported API value returned is false
The Time
  • 697
  • 5
  • 12
  • 26
  • 1
    It looks like you posted your real MySQL database login credentials in your original PHP code snippet. If that's the case then make sure to change your MySQL user password as soon as possible. – tiguchi Apr 29 '15 at 17:57
  • `conn.getResponseCode()` does not say very much about what the php script did. You are not reading the echo()'s of the script so how would you know what happened? – greenapps Apr 29 '15 at 18:11
  • 1
    @Nobu: I have put the wrong credentials there nothing is right :) – The Time Apr 29 '15 at 18:22
  • `I am getting this json string '{"mac": "23:A5:J0:06:C6:E9", "latitude":84.16898451,"longitude":3.16561387,"route": 1}' as output in the doInBackground method `. No. You are getting that as input of your doInBackground. And you try to send that to your script. But do you receive it? Does the php script receive that? How do you check? You are not checking it at all. You could echo it to check. But you are not reading those echos. You dont know what is happening in this way. – greenapps Apr 29 '15 at 19:09
  • You should post the logcatt as you have an IOException now. – greenapps Apr 29 '15 at 19:50
  • @greennapps: in my Logcat output is just the JSON string and the output of getResponseCode `200` – The Time Apr 29 '15 at 20:01
  • Impossible. Then you use other code then you posted here. – greenapps Apr 29 '15 at 20:12
  • `The output of : doInBackground ` That is ia silly statem,ent. I told you that before. But you are not reactiong at all. – greenapps Apr 29 '15 at 20:13
  • @greenapps: please see my Logcode again I thout you are just interested in the output sorry. And when I put the`URL` in the browser I am geting `execute() failed: Column 'mac' cannot be null` what does that mean? The mac column in my table is `NOT NULL`? – The Time Apr 29 '15 at 20:24
  • `ProtocolException`. That you have an exception you were already told. And also how to solve it. – greenapps Apr 29 '15 at 20:30
  • aren't we going a little bit off-topic? This has nothing to do with the original question... – user2340612 Apr 29 '15 at 20:36
  • You think so? The question was wrong as something different was happening than OP thought: Exception. – greenapps Apr 29 '15 at 20:44
  • @greenapps I didn't want to criticize, I just wanted to say that the code has certainly different errors, but they are independent from the original question. In other words even if he solves these problems, he would have no answer to the original question (how can I check if mysql operation worked) – user2340612 Apr 29 '15 at 20:54
  • Then you did not read all the comments here as i already gave hints for that. We could not go into that too deep as first this exception has to be solved. – greenapps Apr 29 '15 at 20:58
  • Ok I am getting now the response `table exist` :) but I dont know why I am getting this error `execute() failed: Column 'mac' cannot be null` when I put the url in the browser? This column is `NOT NULL` in my table. – The Time Apr 29 '15 at 21:00
  • @greenapps Yes, you're right, he needs to solve this exception before all! But then a solution for the ProtocolException could be found [here](http://stackoverflow.com/questions/11413028/cannot-write-output-after-reading-input). I'm suggesting the OP to use the search function ;) – user2340612 Apr 29 '15 at 21:03

2 Answers2

0

Since mysqli_stmt::execute returns a boolean, you can use it in order to make your PHP page respond with something (e.g. a status code) that indicates if the operation was successful or not (in this case you can also provide an explanation for the error). Please note that in both cases the HTTPURLConnection will be "successful" (that's why you get The output of getResponsecode: 200), since your device has been able to reach the server, and the error has been generated on server-side.

EDIT:

The Exception you get is because you are trying to write to the output stream (i.e. to the server) AFTER getting the response. If you want to send some content to the server you need to write it BEFORE getting the response. Hence if you want to print out the response, then you need to replace this line

DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

with this one

DataOutputStream wr = new DataOutputStream(conn.getInputStream());

Furthermore the problems you get on server-side are caused by the fact that you don't send anything to the server, so you need to fix your android app code

user2340612
  • 10,053
  • 4
  • 41
  • 66
  • and how can I see this status code in my eclipse Android output? How can I integrate that in the code to see it in eclipse? – The Time Apr 29 '15 at 17:51
  • The server will respond with something (whathever you `echo` or `print`, such as this "status code"), and you will be able to read this response via the `inputStream` associated to your `conn` (see [this link](http://developer.android.com/reference/java/net/URLConnection.html#getInputStream())). Then you can read it as usual with an `InputStream` (e.g. `BufferedInputStream`) and print to the LogCat if you want – user2340612 Apr 29 '15 at 17:55
  • Ugh... I clearly need more coffee. I deleted what I said to reduce further confusion :-D Sorry about that! – tiguchi Apr 29 '15 at 18:10
  • @NobuGames Don't worry, no problem ;-) – user2340612 Apr 29 '15 at 18:11
  • @But the data is there why is is not being sent to the server? – The Time Apr 29 '15 at 21:05
  • They are not being sent to the server because you are trying to send them AFTER receiving the response. You should move those lines of code BEFORE asking for a response – user2340612 Apr 29 '15 at 21:14
0

You are using twice json_decode() on your input.

You have an IOException cannot write request body after response has been readcaused byy statement System.out.println("The output of getResponsecode: "+conn.getResponseCode());. You can not ask for a response if you have noty send anything yet. Or better: you cannot write anything more after that statement. Put that statement after wr.close(). Then after that read the response form conn.getInputStream().

greenapps
  • 11,154
  • 2
  • 16
  • 19