本人有若干成套學(xué)習(xí)視頻, 可試看! 可試看! 可試看, 重要的事情說三遍 包含Java, 數(shù)據(jù)結(jié)構(gòu)與算法, iOS, 安卓, python, flutter等等, 如有需要, 聯(lián)系微信tsaievan.
HTTPS是基于HTTP的, 它與HTTP不同之處在于HTTP層和TCP層中間多了一個(gè)安全套接字層

HTTPS和HTTP的主要區(qū)別
- HTTPS協(xié)議需要到CA(證書發(fā)布機(jī)構(gòu))申請證書
- HTTP是明文傳輸, HTTPS則是具有SSL加密傳輸協(xié)議
- 連接方式不同,所用端口,HTTP是80端口,HTTPS是443端口
HTTPS請求在客戶端和服務(wù)器之間的交互過程

簡單說來, 就是在客戶端和服務(wù)器之間建立一個(gè)安全通道, 建立通道的機(jī)制就是公鑰和私鑰, 但是服務(wù)器如何將公鑰傳給客戶端呢? 如何保證公鑰在傳輸?shù)倪^程中不會(huì)被攔截呢? 這就需要CA頒發(fā)數(shù)字證書了.
數(shù)字證書你可以理解為一個(gè)被CA用私鑰加密了服務(wù)器端公鑰的密文
當(dāng)服務(wù)器拿到了這個(gè)密文之后就可以發(fā)送給客戶端了, 即使被攔截,沒有CA的公鑰也是無法解開的當(dāng)客戶端拿到了服務(wù)器端的公鑰了之后, 對數(shù)據(jù)進(jìn)行公鑰加密發(fā)送給服務(wù)器端, 服務(wù)器端進(jìn)行私鑰解密.
當(dāng)服務(wù)器端要返回?cái)?shù)據(jù)給客戶端時(shí), 先用私鑰加密,傳輸給客戶端之后, 客戶端再用公鑰解密
以上就是整個(gè)通訊過程
那么我們?nèi)绾瓮ㄟ^NSURLSession和AFN框架來發(fā)送HTTPS請求呢?
- 先說NSURLSession
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self urlSession];
}
- (void)urlSession {
/* 我們以購買火車票的url地址為例 */
NSURL *url = [NSURL URLWithString:@"https://kyfw.12306.cn/otn/"];
/* 發(fā)送HTTPS請求是需要對網(wǎng)絡(luò)會(huì)話設(shè)置代理的 */
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
[dataTask resume];
}
當(dāng)我們遵守了NSURLSessionDataDelegate的時(shí)候
會(huì)走- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler這么一個(gè)代理回調(diào)
在challenge這個(gè)參數(shù)里有一個(gè)protectionSpace(受保護(hù)空間)這么一個(gè)屬性,我們先打印一下看看有什么

可以看到有主機(jī)名, 服務(wù)器請求方法, 認(rèn)證方案, 端口443,代理,代理類型等內(nèi)容. 我們可以看到認(rèn)證方案為NSURLAuthenticationMethodServerTrust
當(dāng)認(rèn)證方案為NSURLAuthenticationMethodServerTrust這個(gè)時(shí), 我們需要調(diào)用completionHandler這個(gè)block, 并傳遞兩個(gè)參數(shù)
-
NSURLSessionAuthChallengeDisposition是一個(gè)枚舉, 告訴我們?nèi)绾翁幚頂?shù)字證書
typedef NS_ENUM(NSInteger, NSURLSessionAuthChallengeDisposition) {
NSURLSessionAuthChallengeUseCredential = 0, /* Use the specified credential, which may be nil */
NSURLSessionAuthChallengePerformDefaultHandling = 1, /* Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored. */
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, /* The entire request will be canceled; the credential parameter is ignored. */
NSURLSessionAuthChallengeRejectProtectionSpace = 3, /* This challenge is rejected and the next authentication protection space should be tried; the credential parameter is ignored. */
}
我們選擇第一個(gè),使用證書
-
NSURLCredential * _Nullable這個(gè)參數(shù)我們需要傳一個(gè)證書進(jìn)去,如何拿到這個(gè)證書對象呢? 我們使用這個(gè)方法
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
我們拿到這兩個(gè)參數(shù)之后, 調(diào)用block,這樣就完整地發(fā)送了一個(gè)HTTPS請求
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
return;
}
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
運(yùn)行結(jié)果如下

- 使用AFN框架發(fā)送HTTPS請求
- (void)afn {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy.validatesDomainName = NO;
[manager GET:@"https://kyfw.12306.cn/otn/" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if (error) {
NSLog(@"請求失敗:%@",error.localizedDescription);
}
}];
}
其他的都跟HTTP請求一樣, 只是需要設(shè)置三個(gè)屬性
manager.responseSerializer = [AFHTTPResponseSerializer serializer];因?yàn)榻邮盏降氖莌tml數(shù)據(jù), 需要用原始解析,而不是默認(rèn)的JSON解析manager.securityPolicy.allowInvalidCertificates = YES;因?yàn)?2306網(wǎng)站采用的是自認(rèn)證, 所以我們需要允許無效證書, 默認(rèn)是NOmanager.securityPolicy.validatesDomainName = NO;使域名有效,我們需要改成NO,默認(rèn)是YES
這三個(gè)屬性設(shè)置完畢之后, 就可以成功地發(fā)送HTTPS請求了.
運(yùn)行結(jié)果:
