ios – 允许使用AFNetworking的无效证书

前端之家收集整理的这篇文章主要介绍了ios – 允许使用AFNetworking的无效证书前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在使用以下代码
  1. AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
  2. operation.allowsInvalidSSLCertificate=YES;

现在我将AFNetworking更改为2.0的最新版本.使用AFHTTPRequestOperation,operation.allowsInvalidSSLCertificate不再工作.根据我使用的文件

  1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  2. manager.securityPolicy.allowInvalidCertificates = YES;

我的请求代码

  1. AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
  2.  
  3. [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responSEObject) {
  4.  
  5. NSLog (@"success: %@",operation.responseString);
  6.  
  7. }
  8. failure:^(AFHTTPRequestOperation *operation,NSError *error) {
  9. NSLog(@"error: %@",error.description);
  10. }
  11. ];
  12.  
  13. [operation start];
  14. [operation waitUntilFinished];

但是,这对于需要证书的HTTPS不起作用.我该怎么办才能使这项工作?

解决方法

我在[操作开始之前]添加以下代码解决了这个问题;
  1. AFSecurityPolicy *sec=[[AFSecurityPolicy alloc] init];
  2. [sec setAllowInvalidCertificates:YES];
  3. operation.securityPolicy=sec;

这是因为AFHTTPRequestOperationManager未连接到AFHTTPRequestOperation.所以设置管理员的安全证书在请求操作时不能做魔术.所以必须初始化并分配一个到AFHTTPRequestOperation.

希望这个帮助有人:)

猜你在找的iOS相关文章