使用AFN框架来访问不受信任的https网站
当我们使用AFN框架向一个不受信任的https网站发出请求时必须做一些配置与操作才能保证不出错,首先我们要禁用ATS特性,然后:
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//01 创建会话管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//设置反序列化方法
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// 验证方式 AFSSLPinningModeNone:最不严格,只要是信任机构签发的证书就会通过,若是自己服务器生成的证书在这里无法通过验证
// AFSSLPinningModePublicKey:只验证公钥
// AFSSLPinningModeCertificate:最严格:除了验证公钥外,还会验证域名/有效期等信息
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//设置允许不受信任的证书
securityPolicy.allowInvalidCertificates = YES;
//设置不验证域名
securityPolicy.validatesDomainName = NO;
manager.securityPolicy = securityPolicy;
//02 发送GET请求
[manager GET:@"https://kyfw.12306.cn/otn" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"success--%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"failure--%@",error);
}];
}
@end
网友评论