Reputation: 2288
I have been searching over the internet about the right configuration to send a POST to my server using HTTPS, some web pages say i need NSURLCredential
and others say:
Just use a @"https://www.myhttpsite.com/" URL and it should work the same way as normal HTTP urls.
So, how is the right way? i need to send credentials of users from my iOS app to my server to authenticate them, so i need to protect this credentials with the HTTPS.
My server already works fine with the HTTPS using internet browsers.
So far what i have is this:
NSString *user = @"user";
NSString *pass = @"pass";
NSString *postData = [NSString stringWithFormat:@"user=%@&pass=%@", user, pass];
NSURL *url = [NSURL URLWithString:@"https://myserver.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [postData dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"data %@", strData);
}];
Upvotes: 1
Views: 2245
Reputation: 480
Found this to be a good example, why don't you try it out?
NSString *urlstring =[[NSString alloc] initWithFormat:@"userName=%@&password=%@",userName.text,password.text];
NSURL *url=[NSURL URLWithString:@"https://www.example.com/mobile/Login.php"];
NSData *postData = [urlstring dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error;
NSURLResponse *resp;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Upvotes: 1