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

时间:2010-03-30 11:15:57

标签: php iphone objective-c cocoa-touch nsurlrequest

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

有什么想法吗?

6 个答案:

答案 0 :(得分:36)

感谢大家的建议。最后,我设法通过使用给定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);

答案 1 :(得分:4)

这是错误的:

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

长度应以字节表示,而不是以UTF8字符计数。 而不是这一行你应该使用:

NSData *data = [post dataUsingEncoding: NSUTF8StringEncoding]; 

答案 2 :(得分:2)

这一行[request setHTTPBody:[NSData dataWithBytes:data length:[data count]]];对我来说有点不对劲。

我想你想要:[request setAllHTTPHeaderFields:data];

其次,你会发现Cocoa框架在发送它们之前大写你的字段名的第一个字母(恼人地)。您可能需要进行一些更改才能应对。

答案 3 :(得分:2)

如果您要进行大量的表单发布,我建议您跳过NSURLRequest并使用ASIHTTPRequest代替。恕我直言,它有很好的文档记录,并提供了一种直接的方式来与Web服务进行交互。

答案 4 :(得分:1)

这适用于IOS 5.o,用于表单发布和获取数据:

self.requestFor = serviceNameT;

responseData = [[NSMutableData data] retain];

SharedResponsedObject* sharedResponsedObject = [SharedResponsedObject returnSharedInstance];
LoginInfo* loginInfo = (LoginInfo*)sharedResponsedObject.loginInfo;

NSLog(@"DEVICE_TOKEN: %@, loginInfo.sessionId: %@, itemIdT: %@", DEVICE_TOKEN, loginInfo.sessionId, itemIdT);

NSString* requestStr = [NSString stringWithFormat:@"Token=%@&SessionId=%@&ItemId=%@", DEVICE_TOKEN, loginInfo.sessionId, itemIdT];


NSData *myRequestData = [ NSData dataWithBytes: [ requestStr UTF8String ] length: [ requestStr length ] ];

NSMutableURLRequest *request = [[ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:@"http://menca.com:1500/DownloadContent.aspx"]]; 

[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(@"ServerRequestResponse::responseData: %@", content);

谢谢&amp;问候, Arun Dhwaj

答案 5 :(得分:0)

修改:已在OP中修复。


这可能不是你唯一的问题(我不知道我的方法-c),但是这里有:

mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) 
VALUES ($sender, $rcpt, $message)");

你不会引用你的字符串 - MySQL肯定会对此有所了解。

mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) 
VALUES ('$sender', '$rcpt', '$message')");

除此之外,通常,即使您的脚本无法从外部访问,您也不应该信任用户输入,并且在将它们插入SQL语句之前使用mysql_real_escape_string()来转义值以防止SQL注入,或使用prepared statements(首选) - 否则合法数据中的单引号将破坏SQL语句的语法。

完全不合适的参考示例:

mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE) 
VALUES ('" . mysql_real_escape_string($sender) ."',"
." '" . mysql_real_escape_string($rcpt) ."',"
." '" . mysql_real_escape_string($message) ."')");