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
分享到:
评论
shappy1978
  • 浏览: 268725 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

你可能感兴趣的:(iPhone)