NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

来源:互联网 发布:python txt按比例拆分 编辑:程序博客网 时间:2024/06/05 06:36

https网站需要授权。


描述:HTTPS 超文本传输安全协议(缩写:HTTPS,英语:Hypertext Transfer Protocol Secure)是超文本传输协议和SSL/TLS的组合,


HTTPS的主要思想是在不安全的网络上创建一安全信道,并可在使用适当的加密包和服务器证书可被验证且可被信任时,对窃听和中间人攻击提供合理的保护。


HTTPS的信任继承基于预先安装在浏览器中的证书颁发机构(如VeriSign、Microsoft等)(意即“我信任证书颁发机构告诉我应该信任的”)。因此,一个到某网站的HTTPS连接可被信任,如果服务器搭建自己的https 也就是说采用自认证的方式来建立https信道,这样一般在客户端是不被信任的,所以我们一般在浏览器访问一些https站点的时候会有一个提示,问你是否继续。


使用webview加载https站点的时候,也会出现这样的情况,也就是说我们必须在请求的时候将该站点设置为安全的,才能继续访问


所以我们需要在webview开始加载网页的时候首先判断判断该站点是不是https站点,如果是的话,先然他暂停加载,先用


NSURLConnection 来访问改站点,然后再身份验证的时候,将该站点置为可信任站点。然后在用webview重新加载请求。


解决步骤如下:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{        NSString* scheme = [[request URL] scheme];    NSLog(@"scheme = %@",scheme);    //判断是不是https    if ([scheme isEqualToString:@"https"])    {        if (self.authed)        {            return YES;        }                NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.outLink]] delegate:self];        [conn start];        [webView stopLoading];        return NO;    }        return YES;}

变量说明:authed就是一个BOOL类型变量。outlink 是链接地址:https://。。。。。


- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{    if ([challenge previousFailureCount]== 0)    {        _authed = YES;        //NSURLCredential 这个类是表示身份验证凭据不可变对象。凭证的实际类型声明的类的构造函数来确定。        NSURLCredential* cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];        [challenge.sender useCredential:cre forAuthenticationChallenge:challenge];    }}- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{    return request;}- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{        self.authed = YES;    //webview 重新加载请求。    [self.ui_myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.outLink]]];    [connection cancel];}

这样就OK了。


0 0