ios项目绕过证书访问https程序

本文介绍了解决Web项目中信任验证问题的方法,通过实现NSURLConnectionDelegate协议中的方法来处理NSURLAuthenticationMethodServerTrust,提供了两种实现方式:针对单个webview或request请求的解决方案,以及在使用three20库时的全局解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果是单个的webview或者request请求,在请求的文件h中直接实现NSURLConnectionDelegate,并在m中添加下列实现下列两个方法:

 

C代码  收藏代码
  1. - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {  
  2.     return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];  
  3. }  
  4.   
  5. - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {  
  6.     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])  
  7.         //if ([trustedHosts containsObject:challenge.protectionSpace.host])  
  8.             [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]   
  9.                  forAuthenticationChallenge:challenge];    
  10.     [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];  
  11. }  

 上述方法很不爽的是每个请求的地方都要加。

 

如果项目中用到了three20,直接修改“TTRequestLoader.m”即可,这个文件本身就已经实现了NSURLConnectionDelegate,

 

修改如下,只改这一个地方就行,处处可用。

 

C代码  收藏代码
  1. ///////////////////////////////////////////////////////////////////////////////////////////////////  
  2. - (void)connection:(NSURLConnection *)connection  
  3. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{  
  4.     //修改  
  5.     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])  
  6.         [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];  
  7.     [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];  
  8.       
  9.     TTDCONDITIONLOG(TTDFLAG_URLREQUEST, @"  RECEIVED AUTH CHALLENGE LOADING %@ ", _urlPath);  
  10.     [_queue loader:self didReceiveAuthenticationChallenge:challenge];  
  11. }  
  12.   
  13. //添加  
  14. - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {  
  15.     return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];  
  16. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值