HTTPS簡單說明:
HTTPS:URL代表它使用了HTTP,但HTTPS存在不一樣於HTTP的默認端口及一個加密/身份驗證層(在HTTP與TCP之間)。
HTTPS和HTTP的區別主要爲如下四點:
https協議須要到ca申請證書,通常免費證書不多,須要交費。
http是超文本傳輸協議,信息是明文傳輸,https 則是具備安全性的ssl加密傳輸協議。
http和https使用的是徹底不一樣的鏈接方式,用的端口也不同,前者是80,後者是443。
http的鏈接很簡單,是無狀態的;HTTPS協議是由SSL+HTTP協議構建的可進行加密傳輸、身份認證的網絡協議,比http協議安全。
簡單說明:
HTTPS的主要思想是在不安全的網絡上建立一安全信道,並可在使用適當的加密包和服務器證書可被驗證且可被信任時,對竊聽和中間人攻擊提供合理的保護。
HTTPS的信任繼承基於預先安裝在瀏覽器中的證書頒發機構(如VeriSign、Microsoft等)(意即「我信任證書頒發機構告訴我應該信任的」)。
所以,一個到某網站的HTTPS鏈接可被信任,若是服務器搭建本身的https 也就是說採用自認證的方式來創建https信道,這樣通常在客戶端是不被信任的。
-(void)session { //1.肯定請求路徑
NSString *urlStr = @"https://kyfw.12306.cn/otn/"; NSURL *url= [NSURL URLWithString:urlStr]; //2.建立請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.建立session
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //5.解析數據
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); }]; //4.執行task
[dataTask resume]; } #pragma mark - NSURLSessionDataDelegate
//只要請求的地址是HTTPS的, 就會調用這個代理方法 //challenge:質詢 //NSURLAuthenticationMethodServerTrust:服務器信任
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler { NSLog(@"%@",challenge.protectionSpace); if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) return; /* NSURLSessionAuthChallengeUseCredential 使用證書 NSURLSessionAuthChallengePerformDefaultHandling 忽略證書 默認的作法 NSURLSessionAuthChallengeCancelAuthenticationChallenge 取消請求,忽略證書 NSURLSessionAuthChallengeRejectProtectionSpace 拒絕,忽略證書 */ NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,credential); }
若是是使用AFN框架,那麼咱們不須要作任何額外的操做,AFN內部已經作了處理
,示例代碼以下:瀏覽器
-(void)afn { //1.肯定請求路徑
NSString *urlStr = @"https://kyfw.12306.cn/otn/"; NSURL *url= [NSURL URLWithString:urlStr]; //2.建立請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.建立會話管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //是否接受無效的證書
manager.securityPolicy.allowInvalidCertificates= YES; //是否匹配域名
manager.securityPolicy.validatesDomainName = NO; NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]); }]; //4.執行任務
[dataTask resume]; }