当前位置: 代码迷 >> Iphone >> iPhone https联接备忘
  详细解决方案

iPhone https联接备忘

热度:57   发布时间:2016-04-25 06:25:22.0
iPhone https连接备忘

第一次用的时候对http连接的使用和api都不熟悉,很多代码都是网上或者书上抄下来的,使用https连接则用了一个私有的API?[NSURLRequest setAllowsAnyHTTPSCertificate: forHost:],结果被拒,后来在网上有其他的解决方案如下:

http://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert

?

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.

link|flag
?
2?
Thanks a lot, it works perfectly. Just remove the the two ifs and keep only the useCendential part in the didReceiveAuthentificationChallenge callback if you want to accept any https site. –?yonel?Jan 27 at 10:40
?
This is awesome! However, it only works on iPhone and 10.6. Is there a similar work-around for 10.5? –?Dave DeLong?May 12 at 16:22
?margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 5px; padding-right: 6px; padding-bottom: 5px; padding-left: 7px; border-top-width: 0px; border-r
  相关解决方案