iOS-处理HTTPS 请求

一.NSURLSession

初始化NSURLSession,使用NSURLSessionDataTask,遵循NSURLSessionDataDelegate

- (void)sessionHttps{
    NSString *url = @"https://kyfw.12306.cn/otn/index/init";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: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(@"data:%@\nerror:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding],error);
    }];
    [dataTask resume];
}

代理方法

//Challenge 接收质询
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
    NSLog(@"%@",challenge.protectionSpace);
    //如果服务器不信任 即不做任何事
    if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
        return;
    }
    /*NSURLSessionAuthChallengeDisposition 如何处理证书
    NSURLSessionAuthChallengeUseCredential = 0,   使用安装
    NSURLSessionAuthChallengePerformDefaultHandling = 1, 默认忽略
    NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 取消请求
    NSURLSessionAuthChallengeRejectProtectionSpace = 3, 拒绝
    */
    //NSURLCredential 授权信息
    NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}

二.AFN

- (void)afnHttps{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //修改解析方式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置对证书处理方式
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    
    [manager GET:@"https://kyfw.12306.cn/otn/index/init" 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);
    }];
}

你可能感兴趣的:(iOS-处理HTTPS 请求)