2015-01-14 78 views
0

我一直在尋找在大約正確的配置Internet使用HTTPS發送POST到我的服務器發送,一些網頁說,我需要NSURLCredential和其他人說:POST使用NSURLConnection的使用HTTPS

只需使用一個@「https://www.myhttpsite.com/」URL,它應該像普通的HTTP URL一樣工作。

那麼,正確的方式如何?我需要將用戶的憑據從我的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); 
}]; 
+0

看看這個SO後的http://stackoverflow.com/questions/1571336/sending-post-data-from-iphone-over-ssl-https – Raghav

+0

@ Raghav_1357我發現這一點:HTTP:// stackoverflow.com/questions/10063224/ios-https-authentication但是是一個完全不同的解決方案...我應該使用哪一個? –

+0

我發佈了一些代碼的答案,爲什麼你不試試? – Raghav

回答

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

我做了,一切正常,但我怎麼能確定這是使用正確的https協議? –

+0

我懷疑會有任何問題,從我對這個主題的瞭解,我認爲你的數據將是安全的... – Raghav

+0

@FernandoSantiago這不是一個好例子。事實上,它不能正確解決問題,並且還存在一些問題(不正確的字符編碼轉換和不存在的後置數據的表單url編碼)。爲了正確解決問題,您需要使用委託方法並根據所需的身份驗證方法(如果需要)提供用戶證書並實施相應的委託,並執行服務器信任評估以確保您已連接到所需的服務器。 – CouchDeveloper

相關問題