AFNetWorking 中的HTTPS

就是记录下,也是从别人那里学习的。


+ (AFSecurityPolicy *)customSecurityPolicy

{

//先导入证书,找到证书的路径

NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"localhost" ofType:@"cer"];

NSData *certData = [NSData dataWithContentsOfFile:cerPath];

//AFSSLPinningModeCertificate 使用证书验证模式

AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];

//allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO

//如果是需要验证自建证书,需要设置为YES

securityPolicy.allowInvalidCertificates = YES;

//validatesDomainName 是否需要验证域名,默认为YES;

securityPolicy.validatesDomainName = NO;

NSArray *set = [[NSArray alloc] initWithObjects:certData, nil];

securityPolicy.pinnedCertificates = set;

return securityPolicy;

}

+ (void)postWithURLString:(NSString *)urlString

parameters:(id)parameters

success:(void (^)(id responseObject))successBlock

failure:(void (^)(NSError *error))failureBlock

{

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

manager.requestSerializer.timeoutInterval = 15;

//HTTPS SSL的验证,在此处调用上面的代码,给这个证书验证;

[manager setSecurityPolicy:[self customSecurityPolicy]];

[manager POST:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {

successBlock(responseObject);

} failure:^(NSURLSessionDataTask *task, NSError *error) {

failureBlock(error);

}];

}

你可能感兴趣的:(AFNetWorking 中的HTTPS)