您的位置:首页 > 移动开发 > IOS开发

ios-信任服务器证书

2017-12-22 19:53 92 查看
当我们使用https去进行网络请求的时候,都会收到服务器给我们的证书,而这些证书有分为机构认证的证书,也有是自己签发的证书。在ios中如果我们是去请求的有机构认证的去发送https的请求,就不需要去做处理,但是如果是自签证书,我们必须要去做处理,否则的话是拿不到数据的。所以我们需要在一个代理方法中进行处理

//首先创建Session
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];
在下面这个代理方法中进行处理,下面的challenge.protectionSpace表示的是一个安全的空间。

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:
(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
//1.判断服务器的采用的认证方法的方法是否是:信任服务器证书
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

//2.创建身份验证证书
NSURLCredential * credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
//3.进行处理
if(completionHandler)
{   //UseCredential表示的是使用服务器发回的证书
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}

}

}
其中关于NSURLSessionAuthChallengeDisposition是一个枚举有以下的枚举值

NSURLSessionAuthChallengeDisposition (处置):
NSURLSessionAuthChallengeUseCredential
-  使用服务器发回证书(保存在challenge里面)
NSURLSessionAuthChallengePerformDefaultHandling
-  默认处理方式,会忽略证书
NSURLSessionAuthChallengeCancelAuthenticationChallenge
-  取消整个请求,忽略证书
NSURLSessionAuthChallengeRejectProtectionSpace
-  本次拒绝,下次再试
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: