使用带有HTTPS的NSURLConnection发送POST

时间:2015-01-14 20:46:59

标签: ios post https nsurlconnection

我一直在互联网上搜索使用HTTPS向我的服务器发送POST的正确配置,一些网页说我需要NSURLCredential,其他人说:

  

只需使用@“https://www.myhttpsite.com/”网址,它的工作方式应与普通的HTTP网址相同。

那么,正确的方法是怎样的?我需要将用户的凭据从我的iOS应用程序发送到我的服务器进行身份验证,因此我需要使用HTTPS保护此凭据。

我的服务器已经可以使用互联网浏览器使用HTTPS了。

到目前为止,我所拥有的是:

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

1 个答案:

答案 0 :(得分:1)

发现这是一个很好的例子,为什么不试试呢?

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