HTTPS简单说明:
HTTPS:URL代表它使用了HTTP,但HTTPS存在不一样于HTTP的默认端口及一个加密/身份验证层(在HTTP与TCP之间)。
HTTPS和HTTP的区别主要为如下四点:
https协议须要到ca申请证书,通常免费证书不多,须要交费。
http是超文本传输协议,信息是明文传输,https 则是具备安全性的ssl加密传输协议。
http和https使用的是彻底不一样的链接方式,用的端口也不同,前者是80,后者是443。
http的链接很简单,是无状态的;HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议,比http协议安全。
简单说明:
HTTPS的主要思想是在不安全的网络上建立一安全信道,并可在使用适当的加密包和服务器证书可被验证且可被信任时,对窃听和中间人攻击提供合理的保护。
HTTPS的信任继承基于预先安装在浏览器中的证书颁发机构(如VeriSign、Microsoft等)(意即“我信任证书颁发机构告诉我应该信任的”)。
所以,一个到某网站的HTTPS链接可被信任,若是服务器搭建本身的https 也就是说采用自认证的方式来创建https信道,这样通常在客户端是不被信任的。
-(void)session { //1.肯定请求路径
NSString *urlStr = @"https://kyfw.12306.cn/otn/"; NSURL *url= [NSURL URLWithString:urlStr]; //2.建立请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.建立session
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //5.解析数据
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); }]; //4.执行task
[dataTask resume]; } #pragma mark - NSURLSessionDataDelegate
//只要请求的地址是HTTPS的, 就会调用这个代理方法 //challenge:质询 //NSURLAuthenticationMethodServerTrust:服务器信任
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler { NSLog(@"%@",challenge.protectionSpace); if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) return; /* NSURLSessionAuthChallengeUseCredential 使用证书 NSURLSessionAuthChallengePerformDefaultHandling 忽略证书 默认的作法 NSURLSessionAuthChallengeCancelAuthenticationChallenge 取消请求,忽略证书 NSURLSessionAuthChallengeRejectProtectionSpace 拒绝,忽略证书 */ NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential,credential); }
若是是使用AFN框架,那么咱们不须要作任何额外的操做,AFN内部已经作了处理
,示例代码以下:浏览器
-(void)afn { //1.肯定请求路径
NSString *urlStr = @"https://kyfw.12306.cn/otn/"; NSURL *url= [NSURL URLWithString:urlStr]; //2.建立请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.建立会话管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //是否接受无效的证书
manager.securityPolicy.allowInvalidCertificates= YES; //是否匹配域名
manager.securityPolicy.validatesDomainName = NO; NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { NSLog(@"%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]); }]; //4.执行任务
[dataTask resume]; }