用UIWebView忽略无效的服务器证书

我们有一个使用UIWebView来显示内容的iOS应用程序。 我们用代码如下所示的数据加载它:

NSURL *url = [NSURL URLWithString:myURLString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [_webView setDelegate:self]; [_webView loadRequest:request]; 

这用于HTTP请求正常工作,但现在我们使用HTTPS对具有自签名SSL证书的服务器。 当上述运行时, webView:didFailLoadWithError: delegate方法被调用,出现此错误:

该服务器的证书无效。 您可能会连接到假装为“blah.blah.blah.com”的服务器,这可能会使您的机密信息处于危险之中。

我想简单地忽略无效的证书并继续处理请求,就像在移动Safari中可以做的一样。

我已经看到在使用NSURLConnection (例如,请参阅旧iphone 3g上的HTTPS请求)时如何解决此问题,但是如何使用UIWebView呢?

我想我可以重写代码,以便它使用NSURLConnection进行请求,然后通过调用其loadHTMLString:baseURL:方法将结果放入Web视图中,但当页面具有图像,CSS,JavaScript时会变得复杂, 等等。 有更容易的方法吗?

请注意 :此API目前不受支持,应该只能在安全的testing环境中使用。 有关更多详细信息,请参阅此CocoaNetics文章 。

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]]; 将允许您忽略证书错误。 您还需要将以下内容添加到文件的开头,以授予您访问这些私有API的权限:

 @interface NSURLRequest (DummyInterface) + (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host; + (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host; @end 

大家都知道,上述隐藏接口的使用不会被APPLE接受。 他们寻找私人API的使用,这不是一个可以接受的解决scheme。 所以,请不要发布上述解决scheme作为解决这个问题的方法,因为尽pipe它有效,但它会在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 

where resultData是一个你之前实例化的NSMutableData,而url和urlAddress都是你已经实例化并填充到其他地方的东西。

不幸的是,我目前还不知道如何让实际的UIWebView直接加载一个页面,而没有有效的证书。

你的,GC

事实certificate,一旦网站被取消的NSURLConnectionauthentication,UIWebView可以向网站发出请求。 这里有一个完整的解释。

据我所知,这是不可能的只是UIWebView 。 据我所知,你需要使用NSURLConnection来处理所有的HTTP / HTTPS mojo,然后通过-loadHtmlString:baseURL:-loadData:MIMEType:textEncodingName:baseURL:将结果提供给UIWebView