这是对我的服务器的JSON POST请求。它直接来自android应用。
{
"appPackage": "tkstudio.autoresponderforwa",
"messengerPackageName":"com.whatsapp",
"query":{
"sender":"John Smith",
"message":"This is an example!",
"isGroup"; false,
"ruleId": 42
}
}
这是我服务器上的完整代码,不包括数据库连接调用
// database details
......
define("_CONFIG", true);
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$data = json_decode(file_get_contents("php://input"));
$stmt = $db->prepare("SELECT * FROM users");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($query["message"] == $row['reg_username']){
$name = $row['reg_email'];
} else {
$name = "Name not in our database";
}
// make sure data is not empty
if( !empty($data->query) &&
!empty($data->appPackageName) &&
!empty($data->messengerPackageName)
){
// set response code - 200 success
http_response_code(200);
// tell the user
echo json_encode(array("replies" => array(
array("message" => "Success!"),
array("message" => $name)
)
)
);
}
现在,请求来自上面的json文件,直接来自android应用程序
$json = '{
"appPackage": "tkstudio.autoresponderforwa",
"messengerPackageName":"com.whatsapp",
"query":{
"sender":"John Smith",
"message":"This is an example!",
"isGroup": false,
"ruleId": 42
}
}';
$res = json_decode($json);
var_dump($res->query->message);//show string(19) "This is an example!"