今天在加载https站点的时候遇到如下的错误问题。所以对自己之前写的iOS内嵌webview做了一些修改,可以让它加载http站点也可以让它加载https站点、
下面是我加载https站点的时候出现的错误。
error:
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813或者9814)
HTTPS 超文本传输安全协议(缩写:HTTPS,英语:Hypertext Transfer Protocol Secure)是超文本传输协议和SSL/TLS的组合,
HTTPS的主要思想是在不安全的网络上创建一安全信道,并可在使用适当的加密包和服务器证书可被验证且可被信任时,对窃听和中间人攻击提供合理的保护。
HTTPS的信任继承基于预先安装在浏览器中的证书颁发机构(如VeriSign、Microsoft等)(意即“我信任证书颁发机构告诉我应该信任的”)。因此,一个到某网站的HTTPS连接可被信任,如果服务器搭建自己的https 也就是说采用自认证的方式来建立https信道,这样一般在客户端是不被信任的,所以我们一般在浏览器访问一些https站点的时候会有一个提示,问你是否继续。
使用webview加载https站点的时候,也会出现这样的情况,也就是说我们必须在请求的时候将该站点设置为安全的,才能继续访问
所以我们需要在webview开始加载网页的时候首先判断判断该站点是不是https站点,如果是的话,先然他暂停加载,先用 NSURLConnection 来访问改站点,然后再身份验证的时候,将该站点置为可信任站点。然后在用webview重新加载请求。
下面是源码:
#import "ViewController.h"
@interface ViewController () <UIWebViewDelegate,NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@property (nonatomic,strong)IBOutletUIWebView *webView;
@property (nonatomic,strong)NSURLRequest *originRequest;
@property (nonatomic,assign,getter=isAuthed)BOOL authed;
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
}
- (IBAction)buttonClick:(id)sender {
NSURL *url = [NSURLURLWithString:@"https://xxxxxxxxxx.com"];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
[self.webViewloadRequest:request];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSString* scheme = [[request URL] scheme];
NSLog(@"scheme = %@",scheme);
//判断是不是https
if ([scheme isEqualToString:HTTPS]) {
//如果是https:的话,那么就用NSURLConnection来重发请求。从而在请求的过程当中吧要请求的URL做信任处理。
if (! self.isAuthed) {
_originRequest = request;
NSURLConnection* conn = [[NSURLConnectionalloc]initWithRequest:requestdelegate:self];
[conn start];
[self.webViewstopLoading];
return NO;
}
}
return YES;
}
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] == 0) {
_authed = YES;
//NSURLCredential这个类是表示身份验证凭据不可变对象。凭证的实际类型声明的类的构造函数来确定。
NSURLCredential* cre = [NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust];
[challenge.senderuseCredential:creforAuthenticationChallenge:challenge];
}
}
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
NSLog(@"%@",request);
return request;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.authed =YES;
//webview 重新加载请求。
[self.webViewloadRequest:_originRequest];
[connection cancel];
}
@end