iPhone sending POST with NSURLConnection

per_pilot picture per_pilot · Jan 15, 2010 · Viewed 61k times · Source

I'm having some problems with sending POST data to a PHP script with NSURLConnection. This is my code:

    const char *bytes = [[NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n<mydata>%@</mydata>", data] UTF8String];

    NSURL *url = [NSURL URLWithString:@"http://myurl.com/script.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[NSData dataWithBytes:bytes length:strlen(bytes)]];

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);

And my script.php is as simple as this:

<?php
    echo $_POST['mydata'];
?>

This have worked for me in the past, but for some reason the output I get from NSLog(@"responseData: %@", responseData); now is just "<>" instead of "theData".

Probably some lame mistake somewhere but I can't seem to find it? Any ideas?

Answer

Mecki picture Mecki · Jan 15, 2010

Your data is wrong. If you expect the data to be found in the $_POST array of PHP, it should look like this:

const char *bytes = "mydata=Hello%20World";

If you want to send XML Data, you need to set a different HTTP Content Type. E.g. you might set

application/xml; charset=utf-8

If you set no HTTP Content Type, the default type

application/x-www-form-urlencoded

will be used. And this type expects the POST data to have the same format as it would have in a GET request.

However, if you set a different HTTP Content Type, like application/xml, then this data is not added to the $_POST array in PHP. You will have to read the raw from the input stream.

Try this:

NSString * str = [NSString stringWithFormat:@"<?xml version=\"1.0\"?>\n<mydata>%@</mydata>", data];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];

and on the server try the following PHP:

$handle = fopen("php://input", "rb");
$http_raw_post_data = '';
while (!feof($handle)) {
    $http_raw_post_data .= fread($handle, 8192);
}
fclose($handle);

Please note that this only works if the HTTP header of your POST is not application/x-www-form-urlencoded. If it is application/x-www-form-urlencoded then PHP itself reads all the post data, decodes it (splitting it into key/value pairs), and finally adds it to the $_POST array.