UIWebView加载HTTPS
当使用UIWebview加载https的站点时webview总是会报NSURLErrorDomain code=-1202,导致网页加载失败。自己打印错误和网上搜索是因为证书失效,https使用超文本安全传输协议,即超文本传输协议(HTTP)和SSL/TLS的组合,用以提供加密通讯及对网络服务器身份的鉴定。当我们的服务器使用自我签名证书时,而UIWebView不允许使用自签名证书,所以导致加载失败。我们可以使用NSURLConnection通过它的代理canAuthenticateAgainstProtectionSpace可以允许这种情况,从而通过它进行认证。
#import <UIKit/UIKit.h>
#import "MyObject.h"
@interface ViewController :UIViewController<UIWebViewDelegate,NSURLConnectionDelegate>
{
UIWebView *_web;
NSURLConnection *_urlConnection;
NSURLRequest *_request;
BOOL _authenticated;
}
@end
@interfaceViewController ()
@end
@implementation ViewController
@synthesize myobject;
- (void)viewDidLoad
{
[superviewDidLoad];
_web = [[UIWebViewalloc] initWithFrame:CGRectMake(0,0,768,1024)];
_web.delegate =self;
_web.autoresizingMask =UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight;
[self.viewaddSubview:_web];
NSURL* _loadingURL =[NSURLURLWithString:@"https://m.facebook.com/dialog/feed?link=http%3A%2F%2Fwww.facebook.com%2FeNGage.OnePub&description=Werwr4w532545245&access_token=BAAC117qbwhQBAFtqiZAmWH8hOtkJLOcC0OTgmYJxX5IybPlPp2ozoZBewaJXBtOagJ5bJItZCZBJ8o8Sal0c52Tt4h2XbPf2f5osEo1ZB2lQh0hF969zeOpoPu1BsS5Hgtr00U55gYb7ZABsvcFohG&caption=Page%201&name=eNGage&picture=http%3A%2F%2Fc1345842.cdn.cloudfiles.rackspacecloud.com%2Fassets%2Fapps%2Ficons%2F001%2F002%2F707%2Foriginal.png%3F1324531970&actions=%5B%7B%22name%22%3A%22Find%20out%20more%20about%20eNGage%22%2C%22link%22%3A%22http%3A%2F%2Fwww.facebook.com%2FeNGage.OnePub%22%7D%5D&app_id=199938153366036&redirect_uri=fbconnect%3A%2F%2Fsuccess&sdk=2&display=touch"];
//_loadingURL=[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[_loadingURL host]];
_request = [NSMutableURLRequestrequestWithURL:_loadingURL];
[_webloadRequest:_request];
// Do any additional setup after loading the view, typically from a nib.
// UIImageView *uimage=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image27.png"]];
// [self.view addSubview:uimage];
// MyObject *object=[[MyObject alloc]init];
// MyObject *object1=[object retain];
//self.myobject=object;
//myobject = object;
//NSLog(@"******retainCount:%d",[myobject retainCount]);
//NSLog(@"******self.retainCount:%d",[self.myobject retainCount]);
//[object release];
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Webview delegate
// Note: This method is particularly important. As the server is using a self signed certificate,
// we cannot use just UIWebView - as it doesn't allow for using self-certs. Instead, we stop the
// request in this method below, create an NSURLConnection (which can allow self-certs via the delegate methods
// which UIWebView does not have), authenticate using NSURLConnection, then use another UIWebView to complete
// the loading and viewing of the page. See connection:didReceiveAuthenticationChallenge to see how this works.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
NSLog(@"Did start loading: %@ auth:%d", [[requestURL]absoluteString],_authenticated);
if (!_authenticated) {
_authenticated =NO;
_urlConnection = [[NSURLConnectionalloc] initWithRequest:_requestdelegate:self];
[_urlConnectionstart];
returnNO;
}
returnYES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
// 102 == WebKitErrorFrameLoadInterruptedByPolicyChange
NSLog(@"***********error:%@,errorcode=%d,errormessage:%@",error.domain,error.code,error.description);
if (!([error.domainisEqualToString:@"WebKitErrorDomain"] && error.code ==102)) {
//[self dismissWithError:error animated:YES];
}
}
#pragma mark - NURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
NSLog(@"WebController Got auth challange via NSURLConnection");
if ([challengepreviousFailureCount] ==0)
{
_authenticated =YES;
NSURLCredential *credential = [NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust];
[challenge.senderuseCredential:credentialforAuthenticationChallenge:challenge];
} else
{
[[challenge sender]cancelAuthenticationChallenge:challenge];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response;
{
NSLog(@"WebController received response via NSURLConnection");
// remake a webview call now that authentication has passed ok.
_authenticated =YES;
[_webloadRequest:_request];
// Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)
[_urlConnectioncancel];
}
// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed.
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
return[protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust];
}
@end
/*************************************************************other****************************************************/
BOOL _Authenticated; NSURLRequest *_FailedRequest;#pragma UIWebViewDelegate-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {BOOL result = _Authenticated;if (!_Authenticated) {_FailedRequest = request;NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];[urlConnection start];}return result; }#pragma NSURLConnectionDelegate-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {NSURL* baseURL = [NSURL URLWithString:@"your url"];if ([challenge.protectionSpace.host isEqualToString:baseURL.host]) {NSLog(@"trusting connection to host %@", challenge.protectionSpace.host);[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];} elseNSLog(@"Not trusting connection to host %@", challenge.protectionSpace.host);}[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; }-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)pResponse { _Authenticated = YES;[connection cancel];[self.webView loadRequest:_FailedRequest];
}
- (void)viewDidLoad{ [super viewDidLoad]; NSURL *url = [NSURL URLWithString:@"your url"]; NSURLRequest *requestURL = [NSURLRequest requestWithURL:url]; [self.webView loadRequest:requestURL]; // Do any additional setup after loading the view. }
/*************************************************************other****************************************************/
#pragma mark - Webview delegate// Note: This method is particularly important. As the server is using a self signed certificate, // we cannot use just UIWebView - as it doesn't allow for using self-certs. Instead, we stop the // request in this method below, create an NSURLConnection (which can allow self-certs via the delegate methods // which UIWebView does not have), authenticate using NSURLConnection, then use another UIWebView to complete // the loading and viewing of the page. See connection:didReceiveAuthenticationChallenge to see how this works. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {NSLog(@"Did start loading: %@ auth:%d", [[request URL] absoluteString], _authenticated);if (!_authenticated) {_authenticated = NO;_urlConnection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];[_urlConnection start];return NO;}return YES; }#pragma mark - NURLConnection delegate- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; {NSLog(@"WebController Got auth challange via NSURLConnection");if ([challenge previousFailureCount] == 0){_authenticated = YES;NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];} else{[[challenge sender] cancelAuthenticationChallenge:challenge];} }- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; {NSLog(@"WebController received response via NSURLConnection");// remake a webview call now that authentication has passed ok._authenticated = YES;[_web loadRequest:_request];// Cancel the URL connection otherwise we double up (webview + url connection, same url = no good!)[_urlConnection cancel]; }// We use this method is to accept an untrusted site which unfortunately we need to do, as our PVM servers are self signed. - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; }
转载于:https://www.cnblogs.com/lkjson/p/4337752.html
UIWebView加载HTTPS相关推荐
- UIWebView加载HTTPS站点出现NSURLErrorDomain code=-1202 SSL
最近在做push 信息到facebook中.当使用UIWebview加载https的站点时webview总是会报NSURLErrorDomain code=-1202,导致网页加载失败.自己打印错误和 ...
- 关于使用UIWebView加载HTTPS站点出现NSURLErrorDomain code=-1202
最近在做push 信息到facebook中.当使用UIWebview加载https的站点时webview总是会报NSURLErrorDomain code=-1202,导致网页加载失败.自己打印错误和 ...
- 关于使用UIWebView加载HTTPS站点
http://blog.sina.com.cn/s/blog_9d4a523e0101emf7.html 转载于:https://www.cnblogs.com/spiderdzl/p/4762315 ...
- uiwebview 读取本地html,UIWebView加载本地HTML文件
一.准备HTML文件及其资源文件 使用UIWebView加载本地的HTML文件 index.html,在index.html中引用了本地的图片.CSS文件.JS文件以及外部的图片. index.htm ...
- 使用UIWebView加载网页
1.使用UIWebView加载网页 运行XCode 4.3,新建一个Single View Application,命名为WebViewDemo. 2.加载WebView 在ViewControlle ...
- 解决ImageLoader加载HTTPS图片证书校验异常问题
解决ImageLoader加载HTTPS图片证书校验异常问题 参考文章: (1)解决ImageLoader加载HTTPS图片证书校验异常问题 (2)https://www.cnblogs.com/cs ...
- Android WebView 加载https网页白屏,空白解决方案
最近在做一个H5相关的需求,使用WebView加载第三方提供的https网页时显示白屏.但是调试打开Baidu和B站的https网址时就能正常打开.被这个问题困扰了半天. 合作方说是android手机 ...
- 成功解决Glide3.7.0加载https图片,显示占位图问题。
平时我们使用Glide加载http网址的图片的时候,图片可以正常加载出来,但是如果服务器端加上了安全认证,当加载自签名的https图片的时候就会报如下错误(证书路径验证异常). Trust ancho ...
- 使用Glide加载https网址图片
最近有网友问我怎么加载https图片,说是从网上找了很多办法都没成功,然后我就问他用的是什么图片加载工具,回答是glide,然后我自己也去网上找了一下,千篇一律的都说是结合okhttp来使用,修改 ...
最新文章
- 数据结构之【栈】的基本操作C语言实现
- 从某一日期开始过day天的日期
- 我的世界minecraft-Python3.9编程(2)-开发环境配置(2)
- vb.net 2019-机器学习ml.net情绪分析(3)
- SAP Spartacus Popover Component 显示与否的逻辑判定
- MySQL命令行导出数据库
- python中decode的用法_python中list怎么使用decode方法设置编码
- java excel 多个sheet_Java Excel导出多个工作表(添加多个sheet)
- linux的虚拟内存是4G,而每个进程都有自己独立的4G内存空间,怎么理解?
- redis 条件查询
- 如何升级浏览器_涨姿势|教你用手机一键升级路由器软件(固件)
- Pyqt 的QThread vs Python标准库的线程
- 离线地图开发之标注柱状图特效(源代码)
- ojdbc6不能使用的解决办法
- 【愚公系列】2022年10月 微信小程序-电商项目-商品详情页面说明和商品导航
- java大作穿越arpg,超任帝国最后的挽歌 篇二:ARPG篇(动作角色扮演游戏)
- GBase 8c数据库登陆
- 用计算机做图画ppt,用计算机画图课件.ppt
- IE8经常无故卡死终极解决办法分享
- 火狐怎么打开html页面,电脑如何设置火狐浏览器主页|电脑设置火狐启动页面的方法...
热门文章
- [AIR应用] Air ANE扩展 for windows
- 用python画雪人-pygame画雪人_函数与图形示例.py
- MATLAB利用nctoolbox读取ECMWF数据的一些问题
- 查看oracle数据库启动状态,Oracle数据库的状态查询
- 【内含福利】A day in Zilliz as a software engineer
- 简要说明第三方收款码,固定收款码、收款二维码的未来发展
- 2022年全球市场维生素贴片总体规模、主要生产商、主要地区、产品和应用细分研究报告
- Python3.绘图基础matplotlib.pyplot
- Java并发编程(多线程) -- 第四部分(JUC - 1)
- 微信客户端开启vconsole调试