使用 NSURLRequest 将键值对传递给具有 POST 的 PHP 脚本

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

有什么想法吗?


答案 1

谢谢大家的建议。最后,我设法通过使用这里给出的东西来解决这个问题。

法典:

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);

答案 2

这是错误的:

[NSData dataWithBytes:[post UTF8String] length:[post length]]

长度应以字节表示,而不是以 UTF8 字符计数表示。您应该使用以下命令来代替此行:

NSData *data = [post dataUsingEncoding: NSUTF8StringEncoding]; 

推荐