How to use NSURLConnection to connect with SSL for an untrusted cert?

后端 未结 13 1811
盖世英雄少女心
盖世英雄少女心 2020-11-22 01:29

I have the following simple code to connect to a SSL webpage

NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
[ NSURLConnection send         


        
13条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 01:59

    There is a supported API for accomplishing this! Add something like this to your NSURLConnection delegate:

    - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
      return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
    }
    
    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
      if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
        if ([trustedHosts containsObject:challenge.protectionSpace.host])
          [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    
      [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
    

    Note that connection:didReceiveAuthenticationChallenge: can send its message to challenge.sender (much) later, after presenting a dialog box to the user if necessary, etc.

提交回复
热议问题