gpt4 book ai didi

php - 使用 NSURLRequest 通过 POST 将键值对传递给 PHP 脚本

转载 作者:IT王子 更新时间:2023-10-29 00:15:04 26 4
gpt4 key购买 nike

我是 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"
?>

有什么想法吗?

最佳答案

感谢大家的建议。最后我设法通过使用给出的东西解决了这个问题 here .

代码:

NSString *myRequestString = @"sender=my%20sender&rcpt=my%20rcpt&message=hello";
NSData *myRequestData = [ NSData dataWithBytes: [ myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString: @"http://people.bath.ac.uk/trs22/insert.php" ] ];
[ request setHTTPMethod: @"POST" ];
[ request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[ request setHTTPBody: myRequestData ];
NSURLResponse *response;
NSError *err;
NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSLog(@"responseData: %@", content);

关于php - 使用 NSURLRequest 通过 POST 将键值对传递给 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2544650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com