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

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


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


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


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.