本人有若干成套學習視頻, 可試看! 可試看! 可試看, 重要的事情說三遍 包含Java
, 數(shù)據(jù)結(jié)構(gòu)與算法
, iOS
, 安卓
, python
, flutter
等等, 如有需要, 聯(lián)系微信tsaievan
.
HTTPS是基于HTTP的, 它與HTTP不同之處在于HTTP層和TCP層中間多了一個安全套接字層
HTTPS和HTTP的主要區(qū)別
- HTTPS協(xié)議需要到CA(證書發(fā)布機構(gòu))申請證書
- HTTP是明文傳輸, HTTPS則是具有SSL加密傳輸協(xié)議
- 連接方式不同,所用端口,HTTP是80端口,HTTPS是443端口
HTTPS請求在客戶端和服務(wù)器之間的交互過程
簡單說來, 就是在客戶端和服務(wù)器之間建立一個安全通道, 建立通道的機制就是公鑰和私鑰, 但是服務(wù)器如何將公鑰傳給客戶端呢? 如何保證公鑰在傳輸?shù)倪^程中不會被攔截呢? 這就需要CA頒發(fā)數(shù)字證書了.
數(shù)字證書你可以理解為一個被CA用私鑰加密了服務(wù)器端公鑰的密文
當服務(wù)器拿到了這個密文之后就可以發(fā)送給客戶端了, 即使被攔截,沒有CA的公鑰也是無法解開的當客戶端拿到了服務(wù)器端的公鑰了之后, 對數(shù)據(jù)進行公鑰加密發(fā)送給服務(wù)器端, 服務(wù)器端進行私鑰解密.
當服務(wù)器端要返回數(shù)據(jù)給客戶端時, 先用私鑰加密,傳輸給客戶端之后, 客戶端再用公鑰解密
以上就是整個通訊過程
那么我們?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ò)會話設(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];
}
當我們遵守了NSURLSessionDataDelegate
的時候
會走- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
這么一個代理回調(diào)
在challenge
這個參數(shù)里有一個protectionSpace
(受保護空間)這么一個屬性,我們先打印一下看看有什么
可以看到有主機名, 服務(wù)器請求方法, 認證方案, 端口443,代理,代理類型等內(nèi)容. 我們可以看到認證方案為NSURLAuthenticationMethodServerTrust
當認證方案為NSURLAuthenticationMethodServerTrust
這個時, 我們需要調(diào)用completionHandler這個block, 并傳遞兩個參數(shù)
-
NSURLSessionAuthChallengeDisposition
是一個枚舉, 告訴我們?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. */
}
我們選擇第一個,使用證書
-
NSURLCredential * _Nullable
這個參數(shù)我們需要傳一個證書進去,如何拿到這個證書對象呢? 我們使用這個方法
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
我們拿到這兩個參數(shù)之后, 調(diào)用block,這樣就完整地發(fā)送了一個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);
}
運行結(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è)置三個屬性
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
因為接收到的是html數(shù)據(jù), 需要用原始解析,而不是默認的JSON解析manager.securityPolicy.allowInvalidCertificates = YES;
因為12306網(wǎng)站采用的是自認證, 所以我們需要允許無效證書, 默認是NOmanager.securityPolicy.validatesDomainName = NO;
使域名有效,我們需要改成NO,默認是YES
這三個屬性設(shè)置完畢之后, 就可以成功地發(fā)送HTTPS請求了.