【问题标题】:How https request is handling using NSURLConnection如何使用 NSURLConnection 处理 https 请求
【发布时间】:2014-01-09 12:45:40
【问题描述】:

谁能帮助我了解如何使用 NSRULConnection 处理 https 请求?我已经阅读了很多教程和 Apple 文档。但我无法理解它是如何工作的。我已经实现了以下委托来处理 https 请求。

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
{    
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{       
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

当我实现上述委托时,我成功地得到了服务器的响应。谁能帮我知道这是如何工作的。委托中的每个参数是什么以及它在做什么?

提前致谢。

【问题讨论】:

    标签: ios objective-c https nsurlconnectiondelegate


    【解决方案1】:

    protectionSpace 视为服务器。委托方法connection: canAuthenticateAgainstProtectionSpace 用于询问您是否可以处理服务器的身份验证要求。在您的情况下,您说“如果我们谈论的是 SSL 证书(这就是 NSURLAuthenticationMethodServerTrust 通常的意思),是的,我可以处理”。

    然后,连接会要求您使用connection:didReceiveAuthenticationChallenge 执行,并为此特定服务器提供 NSURLCredential。使用credentialForTrust:,您可以使用存储在钥匙串中的信息来创建该服务器的证书。使用useCredential:forAuthenticationChallenge:,您最终告诉连接使用此凭据回答挑战,即使用钥匙串数据验证证书。

    【讨论】:

    • 感谢 Dorian 的解释。你能对 NSURLAuthenticationChallenge 一词多解释一下吗?
    • 另外我还有一些疑问,我们是否需要在钥匙串上添加证书以进行 https 连接?我的假设是我必须使用 SSL 证书。如果我们想使用自定义用户凭证,我们只需要实现上面提到的委托还是只需要连接:willsendrequestforauthenticationchallenge?
    • 如果您可以使用上述委托方法成功发出 https 请求,则无需添加证书,因为 ios 似乎知道其根 CA。如果服务器要求用户提供凭据,那是另一种身份验证挑战(例如 NSURLAuthenticationMethodHTTPBasic)。您必须检查该类型,然后提供不同的凭据,例如使用 [NSURLCredential credentialWithUser:password:persistence:]
    【解决方案2】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多