HTTPS

//
//  ViewController.m
//  HTTPS
//
//  Created by hq on 16/4/19.
//  Copyright © 2016年 hanqing. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <NSURLSessionTaskDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    
    NSURLSessionDataTask *task=[session dataTaskWithURL:[NSURL URLWithString:@"https://www.apple.com"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"%@---",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        
    }];
    
    [task resume];

}


/**
 NSURLSessionAuthChallengeDisposition 如何处理这个安全证书
 NSURLCredential 安全证书
 
 */
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    
    //如果不是服务器信任的证书类型,直接返回
    if (![challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        return;
    }
    
    //根据服务器的信任信息创建证书对象
    NSURLCredential *craential=[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    
    if (completionHandler) {
        completionHandler(NSURLSessionAuthChallengeUseCredential,craential);
    }
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

;

Popular Programs