我正在创建简单的应用程序。我有一个接受 5 个参数 'firstname'、'lastname'、'email'、'password' 和 'key' 的 php 脚本。
这是我的 php 文件代码。
<?php
define("SERVER", 'localhost');
define("USER", 'root');
define("PASSWORD", '');
define("DB", 'test');
mysql_connect(SERVER,USER,PASSWORD,DB);
$con = mysql_select_db(DB);
if($_SERVER['REQUEST_METHOD'] == "POST"){
$firstname = isset($_POST['firstname']) ? mysql_real_escape_string($_POST['firstname']) : "";
$lastname = isset($_POST['lastname']) ? mysql_real_escape_string($_POST['lastname']) : "";
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
$key = isset($_POST['key']) ? mysql_real_escape_string($_POST['key']): "";
if(!empty($firstname) && !empty($lastname) && !empty($email) && !empty($password) && !empty($key) ){
if ($key == "12345") {
$sql = "INSERT INTO `users` (`firstname`,`lastname`, `email`, `password`) VALUES ('$firstname', '$lastname', '$email', '$password');";
$qur = mysql_query($sql);
$json = array("status" => 1, "msg" => "Done User added!");
}
else{
$json = array("status" => 0, "msg" =>"key not match");
}
}
else{
$json = array("status" => 0, "msg" => "Error adding user!");
}
}else{
$json = array("status" => 0, "msg" => "Request method not accepted");
}
@mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
这是 Advanced Rest Client 的屏幕截图。
一切都很好。但是当我尝试使用 AFNetworking 从 ios 应用程序发布请求时,我总是得到错误的响应。
这是我的 Objective-C 代码。
NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
[parameters setValue:@"ramu" forKey:@"firstname"];
[parameters setValue:@"kaka" forKey:@"lastname"];
[parameters setValue:@"ramu@gmail.com" forKey:@"email"];
[parameters setValue:@"11111" forKey:@"password"];
[parameters setValue:@"12345" forKey:@"key"];
AFHTTPSessionManager *managertwo = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
managertwo.requestSerializer = [AFJSONRequestSerializer serializer];
[managertwo.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[managertwo POST:[NSString stringWithFormat:@"http://localhost:80/Testing/jsonpost.php"] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"success! %@",responseObject);
NSLog(@"%@",parameters);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error: %@", error);
}];
}
我得到这样的回应
2016-02-16 12:31:36.783 TestingLocal[1626:110064] success! {
msg = "Error adding user!";
status = 0;
}
2016-02-16 12:31:36.783 TestingLocal[1626:110064] {
email = "ramu@gmail.com";
firstname = ramu;
key = 12345;
lastname = kaka;
password = 11111;
}
我不明白为什么会发生这种情况。我到处搜索问题是什么,但我什么也没得到。请帮忙。