iPhone sending POST with NSURLConnection

61,150

Solution 1

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.

Solution 2

Ah yeah... cheers. But the responseData output is like "<48656c6c 6f326f72 6c64>", don't you print NSData with %@? – per_pilot Jan 15 '10 at 13:57

that is because you are showing the "bytes" values you should pass it to NSString to see the real message

NSString *string = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(@"responseData: %@", string);

Solution 3

NSString *post =[NSString stringWithFormat:@"usertype(%@),loginname(%@),password(%@)",txtuser.text,txtusername.text,txtpassword.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.dacinci.com/app/tes2/login_verify.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];

Solution 4

POST data and XML data are not the same. You can send XML data just as you did, but the PHP code must parse the XML from the request body. PHP's xml_parse (http://php.net/manual/en/function.xml-parse.php) can help you do this.

Alternatively, if you would prefer sending POST data, set the request body like this:

const char *bytes = [[NSString stringWithFormat:@"mydata=%@", data] UTF8String];

Solution 5

If you use NSURLSession then in iOS9 set

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
request.HTTPMethod = @"POST";

In PHP set

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
  or die("Unable to connect to MySQL");
  echo "Connected to SQL.";

//select a database to work with
$selected = mysql_select_db($db,$dbhandle) 
  or die("Could not select anons db");
  echo "Connected to DB sucess.";

mysql_query("SET NAMES 'utf8'"); 
mysql_query("SET CHARACTER SET 'utf8'");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci'");

In the db (MySql5) set utf-8_generic.

Share:
61,150
per_pilot
Author by

per_pilot

Updated on January 23, 2020

Comments

  • per_pilot
    per_pilot over 4 years

    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?

  • per_pilot
    per_pilot over 14 years
    Ah yeah... cheers. But the responseData output is like "<48656c6c 6f326f72 6c64>", don't you print NSData with %@?
  • Nils
    Nils over 10 years
    thank you for [request setValue:@"xxx" forHTTPHeaderField:@"Content-Type"];
  • RTOSkit
    RTOSkit almost 10 years
    standard format:...stringWithFormat:@"usertype=%@&loginname=%@&passwo‌​rd=%@" ;)
  • AmyNguyen
    AmyNguyen about 8 years
    Hi, I use "text/xml; charset=utf-8" with HTTP Content-Type, sending request is ok but I use "application/xml; charset=utf-8" and also go together HTTP Content-Type is problem, data returns :"The server cannot service the request because the media type is unsupported". So what s happen?