1

I am just trying to post data on server. This gives no error but data is not getting inserted. I checked using the GET method by directly accessing the php page, it works but when i run the application, it does not work.

PHP Script:



<?php               
        $conn=mysqli_connect("localhost","my_user","my_password","my_db");

                $name=$_POST["name"];
                $age=$_POST["age"];
                $userName=$_POST["userName"];
                $password=$_POST["password"];

                $statement=mysqli_prepare($conn,"INSERT INTO User (name,age,UserName,password) VALUES (?,?,?,?)");
                mysqli_stmt_bind_param($statement,"siss",$name,$age,$userName,$password);
                mysqli_stmt_execute($statement);
                mysqli_stmt_close($statement);
                mysqli_close($conn);

            ?>

But when i manually test it using GET method like http://test.com?user=user1&age=11&userName=wer45&password=23ssds

and change the php scripts as :

<?php   
    $conn=mysqli_connect("localhost","my_user","my_password","my_db");

    $name=$_GET["name"];
    $age=$_GET["age"];
    $userName=$_GET["userName"];
    $password=$_GET["password"];

    $statement=mysqli_prepare($conn,"INSERT INTO User (name,age,UserName,password) VALUES (?,?,?,?)");
    mysqli_stmt_bind_param($statement,"siss",$name,$age,$userName,$password);
    mysqli_stmt_execute($statement);
    mysqli_stmt_close($statement);
    mysqli_close($conn);

?>

Here the above GET works, Can anyone check the below code and help me identify the issue here. i am not able to track as there is no error thrown.

public class storeUserDataAsyncTask extends AsyncTask<Void,Void,Void>{
        User user;
        GetUserCallBack userCallBack;

        public storeUserDataAsyncTask(User user,GetUserCallBack userCallBack){
            this.user=user;
            this.userCallBack=userCallBack;
        }
        @Override
        protected Void doInBackground(Void... params) {
            HashMap<String,String> dataToSend=new HashMap<>();
            dataToSend.put("name", user.name);
            dataToSend.put("age",user.age+"");
            dataToSend.put("userName",user.userName);
            dataToSend.put("password",user.password);
            HttpURLConnection httpURLConnection=null;
            try {
                URL url = new URL("http://nishantapp11.esy.es/Register.php");
                httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(10000);
                httpURLConnection.setReadTimeout(10000);
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                //httpURLConnection.setChunkedStreamingMode(0);

                int serverResponseCode=httpURLConnection.getResponseCode();
                if(serverResponseCode==HttpURLConnection.HTTP_OK){

                }else{
                    Log.e("TAG","not ok");
                }

                OutputStreamWriter outputStreamWriter=new OutputStreamWriter(httpURLConnection.getOutputStream());
                outputStreamWriter.write(getPostDataString(dataToSend));
                outputStreamWriter.flush();

               /* OutputStream outputStream=httpURLConnection.getOutputStream();


                BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
                bufferedWriter.write(getPostDataString(dataToSend));
                bufferedWriter.flush();
                bufferedWriter.close();*/

            }catch (Exception e){
                e.printStackTrace();
            }
            finally {
                httpURLConnection.disconnect();
            }
            return null;
         }

        @Override
        protected void onPostExecute(Void aVoid) {
            progressDialog.dismiss();
            userCallBack.done(null);
            super.onPostExecute(aVoid);
        }
        private String getPostDataString(HashMap<String,String> params) throws UnsupportedEncodingException{

            StringBuilder result=new StringBuilder();
            boolean first =true;
            for(HashMap.Entry<String,String> entry:params.entrySet()) {
                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));

            }
            //Log.e("POST URL", result.toString());
            return result.toString();

        }
    }
sonu patel
  • 23
  • 4
  • are you having any form? if yes then show it code. – Alive to die - Anant Feb 16 '16 at 18:16
  • Welcome to stack overflow. Please read the faq, tour and help sections. In cases like this, it helps to isolate the issue. Use wireshark to see if something comes out of the android code. Use postman to generate HTTP post and see if this works. Check if the php code is run using a debugger or log entries. This will allow you to be more specific. Oh, and check if it isn't related to cookies on Android... – Roy Falk Feb 16 '16 at 18:26
  • I don't think there is any problem with form data. Because when I print the POST URL , it displays the string as expected such as name=name1&age=11&userName=test1&password=pass – sonu patel Feb 17 '16 at 08:09
  • @Roy Falk I tested with postman , the data request and response are working fine.. can you tell me if anything is wrong with the coding part – sonu patel Feb 17 '16 at 09:41

1 Answers1

0

Looking at a sample HTTPURLConnection, there's a httpURLConnection.connect(); at the end which I do not see in your code.

Note that your code has httpURLConnection.disconnect(); in the catch part of the exception.

Disclaimer: Assuming you code is complete and I'm correct

Had you actually used wireshark, you would have seen no traffic coming out of your emulator. This is why it's a very useful tool. It can provide information when your code has no errors or exceptions, but is just missing something.

Community
  • 1
  • 1
Roy Falk
  • 1,685
  • 3
  • 19
  • 45
  • Yes this was one of the mistakes but after that I encountered others too. Thank you for telling about Wireshark it helped a lot to debug – sonu patel Feb 18 '16 at 02:45