1. 程式人生 > >iOS 開發 HTTPS請求詳解

iOS 開發 HTTPS請求詳解

HTTPS

  • HTTPS : Hyper Text Transfer Protocol over Secure Socket Layer,是以安全為目標的HTTP通道,簡單講是HTTP的安全版.即HTTP下加入SSL層,HTTPS的安全基礎是SSL.
  • SSL : Secure Sockets Layer,表示安全套接層.
  • TLS : Transport Layer Security,是SSL的繼任者,表示傳輸層安全.
  • SSL與TLS是為網路通訊提供安全及資料完整性的一種安全協議。TLS與SSL在傳輸層對網路連線進行加密.

HTTPS和HTTP區別

這裡寫圖片描述

HTTPS訪問圖解

這裡寫圖片描述

NSURLSession 實現 HTTPS 訪問

#import "ViewController.h"

@interface ViewController () <NSURLSessionDataDelegate>

@property (nonatomic, strong) NSURLSession *session;

@end

@implementation ViewController

- (NSURLSession *)session {
    if (_session == nil) {
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        _session = [NSURLSession sessionWithConfiguration:config delegate:self
delegateQueue:nil]; } return _session; } - (void)viewDidLoad { [super viewDidLoad]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.session finishTasksAndInvalidate]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self
HTTPSDemo]; } - (void)HTTPSDemo { // URL NSURL *URL = [NSURL URLWithString:@"https://mail.itcast.cn"]; // 自定義session發起任務 (因為我們要在代理方法裡面挑戰伺服器) NSURLSessionDataTask *dataTask = [self.session dataTaskWithURL:URL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // 處理響應 if (error == nil && data != nil) { // 反序列化 NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",html); }else { NSLog(@"%@",error); } }]; // 啟動任務 [dataTask resume]; } #pragma NSURLSessionDataDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler { // 1.判斷接收伺服器挑戰的方法是否是信任證書 if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { // 2.如果你信任證書,就從受保護空間裡面拿出證書,回撥給伺服器,告訴服務,我信任你,你給我傳送資料吧. NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; // 3.把證書回調出去 completionHandler(NSURLSessionAuthChallengeUseCredential,credential); } } @end

AFNetworking之HTTPS請求

- (void)loadData {
    // 建立網路請求mansger
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 使AFN支援HTTPS請求 : 2.5.4之前
    // manager.securityPolicy.allowInvalidCertificates = YES;

    // 使AFN支援HTTPS請求 : 2.6.1以後
    manager.securityPolicy.validatesDomainName = NO;

    // 修改AFN預設支援接收的文字型別
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html" ,nil];

    // 修改AFN預設處理資料的方式 : 設定成只返回原始的二進位制資料,程式猿自己反序列化
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    // 網路請求地址
    NSString *URLStr = @"https://mail.itcast.cn";

    [manager GET:URLStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        // NSLog(@"%@ %@",[responseObject class],responseObject);

        // 反序列化
        NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",html);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"出錯 %@",error);
    }];
}