Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

like image 570
Ralf Mclaren Avatar asked Mar 30 '10 11:03

Ralf Mclaren


5 Answers

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);
like image 89
Ralf Mclaren Avatar answered Oct 24 '22 03:10

Ralf Mclaren


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:

NSData *data = [post dataUsingEncoding: NSUTF8StringEncoding]; 
like image 20
Krešimir Prcela Avatar answered Oct 24 '22 04:10

Krešimir Prcela


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

I think you want: [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.

like image 37
Nick Moore Avatar answered Oct 24 '22 02:10

Nick Moore


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

like image 38
Victor Jalencas Avatar answered Oct 24 '22 02:10

Victor Jalencas


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

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

like image 1
Arun Dhwaj Avatar answered Oct 24 '22 02:10

Arun Dhwaj