使用NSURLRequest将键值对通过POST传递到PHP脚本 [英] Using NSURLRequest to pass key-value pairs to PHP script with POST

查看:165
本文介绍了使用NSURLRequest将键值对通过POST传递到PHP脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对objective-c很新,我想使用POST传递一些键值对到PHP脚本。我使用下面的代码,但数据似乎没有被发布通过。我尝试通过使用NSData发送的东西,但也似乎没有工作。

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.

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

这是发送到这个简单的脚本来执行db插入:

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

任何想法?

推荐答案

感谢大家的建议。最后,我设法解决这个问题,使用这里 a>。

Thanks for the suggestions everyone. In the end i managed to solve the issue by using stuff given 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);

这篇关于使用NSURLRequest将键值对通过POST传递到PHP脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆