使用 NSURLRequest 将键值对传递给具有 POST 的 PHP 脚本
2022-08-31 00:17:01
我对objective-c相当陌生,并且希望使用POST将许多键值对传递给PHP脚本。我正在使用以下代码,但数据似乎没有通过发布。我也尝试过使用NSData发送东西,但似乎都不起作用。
NSDictionary* data = [NSDictionary dictionaryWithObjectsAndKeys:
@"bob", @"sender",
@"aaron", @"rcpt",
@"hi there", @"message",
nil];
NSURL *url = [NSURL URLWithString:@"http://myserver.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSData dataWithBytes:data length:[data count]]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", content);
它被发送到这个简单的脚本来执行数据库插入:
<?php $sender = $_POST['sender'];
$rcpt = $_POST['rcpt'];
$message = $_POST['message'];
//script variables
include ("vars.php");
$con = mysql_connect($host, $user, $pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE)
VALUES ($sender, $rcpt, $message)");
echo "complete"
?>
有什么想法吗?