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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2544650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:54:30  来源:igfitidea点击:

Using NSURLRequest to pass key-value pairs to PHP script with POST

phpiphoneobjective-ccocoa-touchnsurlrequest

提问by Ralf Mclaren

I'm fairly new to objective-c, and am looking to pass a number of key-value pairs to a PHP script using POST. I'm using the following code but the data just doesn't seem to be getting posted through. I tried sending stuff through using NSData as well, but neither seem to be working.

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

This is getting sent to this simple script to perform a db insert:

这被发送到这个简单的脚本来执行数据库插入:

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

Any ideas?

有任何想法吗?

回答by Ralf Mclaren

Thanks for the suggestions everyone. In the end i managed to solve the issue by using stuff given here.

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

Code:

代码:

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

回答by Prcela

This is wrong:

这是错误的:

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

The length should be expressed in bytes not in count of UTF8 characters. Instead of this line you should use:

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

NSData *data = [post dataUsingEncoding: NSUTF8StringEncoding]; 

回答by Nick Moore

This line [request setHTTPBody:[NSData dataWithBytes:data length:[data count]]];looks way wrong to me.

这条线[request setHTTPBody:[NSData dataWithBytes:data length:[data count]]];在我看来是错误的。

I think you want: [request setAllHTTPHeaderFields:data];

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

Secondly, you will find the Cocoa framework capitalizes the first letter of your field names before sending them (annoyingly). You might have to make some changes to cope with that.

其次,您会发现 Cocoa 框架在发送字段名称之前将它们的首字母大写(令人讨厌)。您可能需要进行一些更改来应对这种情况。

回答by Victor Jalencas

If you are going to do a lot of form posting, I'd recommend skipping NSURLRequest and using ASIHTTPRequestinstead. IMHO, it's well documented and offers an straightforward way to interact with webservices.

如果您要进行大量表单发布,我建议您跳过 NSURLRequest 并改用ASIHTTPRequest。恕我直言,它有据可查,并提供了一种与网络服务交互的直接方式。

回答by Arun Dhwaj

This is working on IOS 5.o for Form Posting and getting the Data:

这是在 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);

Thanks & Regards, Arun Dhwaj

感谢和问候, Arun Dhwaj

回答by pinkgothic

Edit: Has been fixed in OP.

编辑:已在 OP 中修复。



This may not be your sole problem (I don't know my way around objective-c), but here goes:

这可能不是你唯一的问题(我不知道我如何解决 Objective-c),但这里有:

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

You're not quote-enclosing your strings - MySQL is bound to have a hissy fit over that.

你没有用引号括住你的字符串——MySQL 肯定会对此感到厌烦。

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

Beyond that, generally, even if your script is not reachable from the outside, you shouldn't trust user input and either use mysql_real_escape_string()to escape your values before you insert them into the SQL statement to prevent SQL injection, or use prepared statements(preferred) - otherwise single quotes in your legitimate data will break the SQL statement's syntax.

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

Entirely ungraceful example for reference:

完全不雅的例子供参考:

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) ."')");