A知识点2

iOS 关于Https

2016-12-21  本文已影响22人  哔哩哔哩智能喵
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()<NSURLSessionDelegate>

@end

@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self AFNsendHttps];
}
-(void)AFNsendHttps
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //是否信任无效或过期的SSL证书
    manager.securityPolicy.allowInvalidCertificates = YES;
    //是否开启域名验证
    manager.securityPolicy.validatesDomainName = NO;
    //更改解析方式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"https://kyfw.12306.cn/otn" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
         NSLog(@"success---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error---%@",error);
    }];
}
-(void)sendHttps
{
    NSURL *url = [NSURL URLWithString:@"https://kyfw.12306.cn/otn"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    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) {
        NSLog(@"%@---%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],error);
    }];
    [datatask resume];
}
/**
 如果发送的请求是https的,那么才会调用该方法
 *  @param session           会话对象
 *  @param challenge         询问是否安装SSL证书
 *  @param completionHandler 传给系统两个参数
        NSURLSessionAuthChallengeDisposition :如何处理证书
            NSURLSessionAuthChallengeUseCredential = 0, 使用该证书 安装该证书
            NSURLSessionAuthChallengePerformDefaultHandling = 1, 默认采用的方式,该证书被忽略
            NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 取消请求,证书忽略
            NSURLSessionAuthChallengeRejectProtectionSpace = 3,          拒绝
        NSURLCredential :授权信息
 */
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    //判断一下如果身份验证服务器已经信任的话就return出去
    if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
        return ;
    }
    
    NSURLCredential * credential = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
    
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
@end
上一篇下一篇

猜你喜欢

热点阅读