有的时候Https访问我们可以直接拿到数据!!
因为有的公司财大气粗!哥么有钱!!可以认证!!!
认证过的Https访问时强制安装证书的!!
但是很多公司的Https访问你这样是拿不到数据的!!
代码实现
@interface ViewController ()<NSURLSessionTaskDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
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];
}
#pragma mark - <协议>
/**
参数:
Challenge :询问,询问客户端是否需要信任来自服务器的证书!
属性:protectionSpace(受保护的空间)
Auth-Scheme:NSURLAuthenticationMethodServerTrust 服务器返回的授权模式:要求信任服务器的证书
completionHandler : 通过代码块回调,决定对证书的处理!!
NSURLSessionAuthChallengeDisposition (处置):
NSURLSessionAuthChallengeUseCredential
- 使用服务器发回证书(保存在challenge里面)
NSURLSessionAuthChallengePerformDefaultHandling
- 默认处理方式,会忽略证书
NSURLSessionAuthChallengeCancelAuthenticationChallenge
- 取消整个请求,忽略证书
NSURLSessionAuthChallengeRejectProtectionSpace
- 本次拒绝,下次再试
NSURLCredential 证书
*/
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
//1.判断服务器的身份验证的方法是否是:信任服务器证书
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSLog(@"哥么是信任的证书");
//2.获得证书
NSURLCredential * credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//3.对服务器的证书做出"处理"
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
}
@end