0

According to http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ , part 6, I want to send user and password, and retrieve status of login; as same as description of part 6!

I'm using volley library, and override getParams function to set Keys Values. And sent as POST to php page.

This is snippet code via volley library:

url = "http://www.myurl.com/app/page.php";
TAG = "tagToCancelReq";
JsonObjectRequest postRequest = new JsonObjectRequest (Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(JsonObject response) {
            // response
            Log.d("Response", response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
            Log.d("Error.Response", response);
       }
    }
) {     
    @Override
    protected Map<String, String> getParams() 
    {  
            Map<String, String>  params = new HashMap<String, String>();  
            params.put("user", "client1");  
            params.put("pass", "123");

            return params;  
    }
};

queue.addToRequest(postRequest,TAG);

This is php code:

**<?php
/* Encode array to JSON string */
function encodearray($posts) {
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));
}
$response = array();
if (isset($_POST['p']) && isset($_POST['v'])) {
    $response["success"] = 1;
    foreach ($_POST as $key => $value)
    {
        $response[$key] = $value;
    }

    $con = mysql_connect("localhost", "username", "password") or die(mysql_error());
    $db = mysql_select_db("db") or die(mysql_error());
    $strsql = "INSERT INTO `users` (";
    $strsql .= implode(",", array_keys($response));
    $strsql .= ") VALUES ('";
    $strsql .= implode("','", array_values($response));
    $strsql .= "')";
    mysql_query($strsql) or die($db->error());

    /* encode the JSON post from the array */
    encodearray($response);
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>**

In this way, server response success = 0.

But when using httpPost and Asynctask like this, server retrieve request and response correctly. Code is:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php");
// Add your data   
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > (5);
nameValuePairs.add(new BasicNameValuePair("user", "client1"));
nameValuePairs.add(new BasicNameValuePair("pass", "123"));


try {
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    Log.d("myapp", "works till here. 2");
        try {
        HttpResponse response = httpclient.execute(httppost);
        Log.d("myapp", "response " + response.getEntity());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
 e.printStackTrace();

}

What is wrong with first way?

Even when i use local web server(wamp server), and change URL to

http://10.0.2.2:80/adnroid_server/get_All.php";

and run app on emulator, in first way (volley), server doesn't response (no error too), and in second way(httPost) every thing is correct and response retrieved.

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
  • 1
    You are using a `JsonObjectRequest` but not sending json. You would send just some name value pairs. Isn't there a 'normal' type of request? – greenapps Jul 02 '14 at 13:48
  • @greenapps I just follow this link: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ number 6.(Adding post parameters) – Dr.jacky Jul 02 '14 at 13:52
  • @greenapps Yes, there is a StringRequest. And that's work! Please post your comment as a answer. Thank you so much. – Dr.jacky Jul 02 '14 at 13:57
  • @greenapps What's your mean "but not sending json"? – Dr.jacky Jul 03 '14 at 13:24
  • While you were sending just some name value pairs. That's no json is it? – greenapps Jul 03 '14 at 13:35
  • @greenapps Please see link on second comment on this post. There are just some name value pairs, but programmer uses JSONObject! By the way, I have to receive json from response. – Dr.jacky Jul 03 '14 at 13:42
  • Indeed I see, The request does not have to be in json format as we read here `If you are expecting json object in the response, you should use JsonObjectRequest class or if the response is json array, JsonArrayRequest class should be used.`Well I don't know why your script fails with volley. – greenapps Jul 03 '14 at 13:56
  • 1
    You have to find out what is different when volley is posting you could do that using temporarily a different script which contains `$data = file_get_contents("php://input");` and then echos $data. See: http://stackoverflow.com/questions/23828801/how-to-receive-zip-file-on-php-server-sent-from-android Hmmm can be that Volley can not handle such no json response and that you cannot see the raw data. Or can you? If you cant then save $data to file on the server (as in the example) and inspect later. – greenapps Jul 03 '14 at 14:10
  • Are you sure that a `JsonArrayRequest` wouldn't be more suitable? And using a string request and invoking json on the received text is always possible. – greenapps Jul 03 '14 at 14:19
  • @Why JsonArrayRequest?! My json response start with { , not [ . I mean my json is like { "tag": "login", "success": 0, "error": 1, "error_msg": "Incorrect email or password!" } – Dr.jacky Jul 03 '14 at 14:44
  • 1
    Well how would i have known that? – greenapps Jul 03 '14 at 14:49
  • @greenapps Sorry :D. According to link on second comment, part 6, I want to send user and password, and retrieve status of login; as same as description of part 6! – Dr.jacky Jul 03 '14 at 14:56
  • Yes I know a long time already that you want to do something like that. What did you change on code that it doesn't work when you try? Maybe you have to start from begin using only androidhive's files. Did you start in that way? – greenapps Jul 03 '14 at 15:02
  • @greenapps As you see, that link have just some description. In another post of site, http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/ ,using NameValuePair. – Dr.jacky Jul 03 '14 at 15:09
  • The getParams does not work as you can read here: http://stackoverflow.com/questions/19837820/volley-jsonobjectrequest-post-request-not-working The androidhive autor is not posting to a script but to a .json file. That will be a normal text file with a textual json object in it. The whole posting of key value pairs is also not done in his example. But that does not matter as he rertrieves a file. Take them out to see. He could have done better. – greenapps Jul 03 '14 at 16:17
  • 1
    Downloaded the androidhive code and started testing. From above mentionend post I took the answer that starts with `You can create a custom JSONObjectReuqest` This works. But with the help of `$data = file_get_contents("php://input");`I found out that volley just sends json object text and so just json object text is received by the script. Nothing of a normal post. So as your script expects a normal post the post parameters are not there. Conclusion: use the String Request. – greenapps Jul 03 '14 at 16:38
  • 1
    If you had taken the time to read the comments on the androidhive page then you would have read `POST. The getParams() method was never being called. I fixed it by creating a JsonObject and passed it in the JsonObjectRequest instead of the parameter which is null.` And had saved your and my time. – greenapps Jul 03 '14 at 16:49
  • @greenapps Is there any way to send data as StringRequest, but retrieve response in json?! – Dr.jacky Jul 03 '14 at 18:15
  • Of course. Your script sends json text. In two of my comments that was already suggested. Do the same as you would do in your async task. Grab the text from the response and give it to the json parser. – greenapps Jul 03 '14 at 18:39

1 Answers1

1

Use a different type of request.

5. Making String request.
greenapps
  • 11,154
  • 2
  • 16
  • 19