当使用UIWebview加载https的站点时webview总是会报NSURLErrorDomain code=-1202,导致网页加载失败。自己打印错误和网上搜索是因为证书失效,https使用超文本安全传 输协议,即超文本传输协议(HTTP)和SSL/TLS的组合,用以提供加密通讯及对网络服务器身份的鉴定。当我们的服务器使用自我签名证书时,而UIWebView不允许使用自签名证书,所以导致加载失败。
解决办法: you're using a self-signed certificate, it's necessary to add some additional code.Because by default iOS will reject all untrusted https connections。重写下面俩个方法:
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace; -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
#import "ClassCon.h" // For now, I've hard coded the IP address of my trusted server. #define TRUSTED_HOST @"192.168.1.2" @implementation ClassCon { NSMutableData *contentData; NSURLConnection *conn; } -(void) loadContent { contentData = [NSMutableData data]; NSString *contentURL = @"our url"; conn = [[NSURLConnection alloc] initWithRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:contentURL]] delegate:self]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [contentData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Bad: %@", [error description]); ContentResponse *response = [[ContentResponse alloc]initWithRc:-999 andDescr:@"error" andAction:0]; conn = nil; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *loadedContent = [[NSString alloc] initWithData: contentData encoding:NSUTF8StringEncoding]; NSLog(@"Loaded content: %@",loadedContent); } // ------------ ByPass ssl starts ---------- -(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])) { if ([challenge.protectionSpace.host isEqualToString:TRUSTED_HOST]) { NSLog(@"Allowing bypass..."); NSURLCredential *credential = [NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust]; [challenge.sender useCredential:credential forAuthenticationChallenge:challenge]; } } [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; } // -------------------ByPass ssl ends @end