您的当前位置:首页正文

AFNetworking2.x的SSL身份认证

2022-06-15 来源:知库网

如果你用的是NSURLConnection,你需要这样检查证书,必须添加一个 NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

用 AFNetworking 2.x的话就简单多了,只需要添加一个AFSecurityPolicy 和 setAFHTTPRequestOperationManager

要经常用的话,推荐写一个方法,然后以后用就可以复制黏贴了

- (AFSecurityPolicy*)customSecurityPolicy
{
 /**** SSL Pinning ****/
 NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"你的证书" ofType:@"cer"];
 NSData *certData = [NSData dataWithContentsOfFile:cerPath];
 AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
 [securityPolicy setAllowInvalidCertificates:NO];
 [securityPolicy setPinnedCertificates:@[certData]];
 [securityPolicy setSSLPinningMode:AFSSLPinningModeCertificate];
 /**** SSL Pinning ****/

 return securityPolicy;
}

然后在管理器里这么设置

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

 /**** SSL Pinning ****/
 [manager setSecurityPolicy:[self customSecurityPolicy]];
 /**** SSL Pinning ****/
 
 [manager GET:@"网站的url" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary* responseObject) {
 //这里是你自己的代码了
 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
 //注释同上
 }];
显示全文