简体   繁体   中英

how to receive json object from android using POST method

I am working on a php script which receives data sent by android in json format using POST method. But i am not getting any data, here is my code

$josn = file_get_contents("php://input");   
$json_data = json_decode($josn, true);   

i just tried to print $json_data by

print_r($json_data);   

but its not showing any values

var_dump() is much more reliable than print_r()

Whether the data is corrupt or not, it will tell you 'something' about the thing you are trying to see.

If it is null it will say ' null '.

If it is ' bob ' it will say (string 3) 'bob' .

If it is 4 it will say (int) 4

If it is ' 4 ' it will say (string 1) '4'

Also, your json_decode() might be breaking if the input is not valid json. A safer way to see if you are getting any data at all is to dump and check your data before you pass it into the json_decode() function:

var_dump( file_get_contents("php://input") );

If you see valid json, then it is safe to pass your $josn variable into the json_decode() function.

Bonus

Seems dumb but it's worth mentioning that you can only use file_get_contents() on the input buffer once and then the contents are gone. If you try to read them again, they will be null. Refer to the variable you stored them in when you first read them.

Separetely

Another fellow mentioned checking your global $_POST[] variable... which brings up a great point. Headers!

For json pickup with file_get_contents('php://input') , php needs your android app to send the header:

header('Content-Type: application/json');

For POST variable pickup with $_POST[] , php needs your android app to send the header:

header('Content-Type: application/x-www-form-urlencoded');

OR

header('Content-Type: multipart/form-data');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM