Search code examples
iphone-sdk-3.0iphone

Sending POST data from iphone over SSL HTTPS


Hai all,

In my iphone project i need to pass the user name and password to a web server,previously i pass data using GET method and used the url with GET format (eg: localhost:8888/login?userName=admin&password=password ) but now i need to sent this as a POST data,

can any one help me to find what wrong in this code below ?

code i tried ..


NSString *post =[NSString stringWithFormat:@"userName=%@&password=%@",userName.text,password.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:@"https://localhost:443/SSLLogin/login.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 *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(data);

this page will return success or failed using php echo


Solution

  • You are sending the request as NSASCIIStringEncoding but looking for NSUTF8StringEncoding

    I'd set

    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    

    and

    [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    

    however, as Nikolai noted - this would be easier if we knew what the error was :-)