使用NSURLSession或者AFN發送HTTPS請求
HTTPS是基于HTTP的, 它與HTTP不同之處在于HTTP層和TCP層中間多了一個 安全套接字層
HTTPS模型
HTTPS和HTTP的主要區別
- HTTPS協議需要到CA(證書發布機構)申請證書
- HTTP是明文傳輸, HTTPS則是具有SSL加密傳輸協議
- 連接方式不同,所用端口,HTTP是80端口,HTTPS是443端口
HTTPS請求在客戶端和服務器之間的交互過程
HTTPS模型
-
簡單說來, 就是在客戶端和服務器之間建立一個安全通道, 建立通道的機制就是公鑰和私鑰, 但是服務器如何將公鑰傳給客戶端呢? 如何保證公鑰在傳輸的過程中不會被攔截呢? 這就需要CA頒發數字證書了.
-
數字證書你可以理解為一個被CA用私鑰加密了服務器端公鑰的密文
當服務器拿到了這個密文之后就可以發送給客戶端了, 即使被攔截,沒有CA的公鑰也是無法解開的
-
當客戶端拿到了服務器端的公鑰了之后, 對數據進行公鑰加密發送給服務器端, 服務器端進行私鑰解密.
-
當服務器端要返回數據給客戶端時, 先用私鑰加密,傳輸給客戶端之后, 客戶端再用公鑰解密
以上就是整個通訊過程
那么我們如何通過NSURLSession和AFN框架來發送HTTPS請求呢?
- 先說NSURLSession
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self urlSession];
}
- (void)urlSession {
/* 我們以購買火車票的url地址為例 */
NSURL *url = [NSURL URLWithString:@"https://kyfw.12306.cn/otn/"];
/* 發送HTTPS請求是需要對網絡會話設置代理的 */
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 這么一個代理回調
在 challenge 這個參數里有一個 protectionSpace (受保護空間)這么一個屬性,我們先打印一下看看有什么
打印內容
可以看到有 主機名, 服務器請求方法, 認證方案, 端口443,代理,代理類型等 內容. 我們可以看到認證方案為 NSURLAuthenticationMethodServerTrust
當認證方案為 NSURLAuthenticationMethodServerTrust 這個時, 我們需要調用completionHandler這個block, 并傳遞兩個參數
- NSURLSessionAuthChallengeDisposition 是一個枚舉, 告訴我們如何處理數字證書
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 這個參數我們需要傳一個證書進去,如何拿到這個證書對象呢? 我們使用這個方法
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
我們拿到這兩個參數之后, 調用block,這樣就完整地發送了一個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);
}
運行結果如下
打印出了網頁內容
- 使用AFN框架發送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請求一樣, 只是需要設置三個屬性
-
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 因為接收到的是html數據, 需要用原始解析,而不是默認的JSON解析
-
manager.securityPolicy.allowInvalidCertificates = YES; 因為12306網站采用的是自認證, 所以我們需要允許無效證書, 默認是NO
-
manager.securityPolicy.validatesDomainName = NO; 使域名有效,我們需要改成NO,默認是YES
這三個屬性設置完畢之后, 就可以成功地發送HTTPS請求了.
運行結果:
運行結果
來自:http://www.jianshu.com/p/d833ac6fa5ab