在寫文章之前要先提醒一下大家,以下的教學目的是不論如何都要去連 HTTPS Server
正常的情況下是會先輸入帳號密碼,而且檢查 Server 的憑證是不是合法之類的
即使不用輸入帳號密碼,如果憑證有可疑,通常 Browser 也會跳出一個視窗來提醒使用者,如下
Firefox 會看到
Safari 會看到
以下的文章是在不用輸入帳號密碼而且不檢查 Server 的憑證的清況下
簡單利用 NSURLConnection 就可以了
- (void)viewDidLoad
{
[super viewDidLoad];
NSString * httpsAddress = @"https://allseeing-i.com";
NSURLConnection * urlCon = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:httpsAddress]] delegate:self];
}
// 一般的 connection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"got data %@", [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"error");
}
// 無論如何回傳 YES
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace{
return YES;
}
// 不管那一種 challenge 都相信
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
NSLog(@"received authen challenge");
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}