我们有一个iOS应用程序,它使用UIWebView来显示内容。我们用如下代码加载数据:
NSURL *url = [NSURL URLWithString:myURLString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView setDelegate:self];
[_webView loadRequest:request];这过去可以很好地处理HTTP请求,但现在我们对具有自签名SSL证书的服务器使用HTTPS。当运行上述操作时,将调用webView:didFailLoadWithError:委托方法,并出现以下错误:
此服务器的证书无效。您可能正在连接到一个假装是“blah.com”的服务器,这可能会使您的机密信息处于危险之中。
我想简单地忽略无效的证书并继续进行请求,就像在Mobile中所做的那样。
我已经了解了如何在使用NSURLConnection时解决这个问题(例如,请参阅老式iPhone3G上的HTTPS请求 ),但是如何处理UIWebView呢?
我设想我可以重新处理代码,以便它使用NSURLConnection发出请求,然后通过调用其loadHTMLString:baseURL:方法将结果放到web视图中,但是当页面有图像、CSS、JavaScript等时,情况会变得复杂。有更简单的方法吗?
发布于 2012-02-08 01:26:47
--请注意:这个API目前不受支持,应该只在安全的测试环境中使用。要了解更多细节,请看一下这个CocoaNetics文章。
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];将允许您忽略证书错误。您还需要将以下内容添加到文件的开头,以授予您访问这些私有API的权限:
@interface NSURLRequest (DummyInterface)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end发布于 2012-04-09 18:22:02
让大家都知道..。以上使用的隐藏接口将不被苹果接受。他们希望使用私有API,这是一个不可接受的解决方案。因此,请不要将上面描述的解决方案作为修复它的方法,因为尽管它有效,但它会在AppStore中给您带来拒绝。这样就没用了。
下面是忽略无效服务器证书的可接受方法。您需要使用NSURLConnection并手动加载网页的数据,如下所示:
.
.
.
    //Create a URL object.
    url = [NSURL URLWithString:urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:requestObj delegate:self];
    [connection start];
}然后,在你的代表里..。
- (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])
    {
        [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
    }
    else
    {
        [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
    }
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
[resultData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    NSString *htmlString = [[NSString alloc] initWithBytes:[resultData bytes] length:[resultData length] encoding:NSUTF8StringEncoding];
    [webView loadHTMLString:htmlString baseURL:url];
}
@end其中resultData是您先前实例化的NSMutableData,而url和urlAddress都是您在其他地方实例化和填充的内容。
不幸的是,我目前还不知道如何让实际的UIWebView在没有有效证书的情况下直接加载页面。
你的,GC
发布于 2013-02-25 19:03:50
事实证明,一旦被取消的NSURLConnection对站点进行了身份验证,UIWebView就可以向站点发出请求。这里有一个完整的解释。
https://stackoverflow.com/questions/6792213
复制相似问题