NSURLSeesion和AFN发送https请求

NSURLSession

-(void)session
{
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    //2.创建url
    NSURL* url=  [NSURL URLWithString:@"https://kyfw.12306.cn/otn/"];
    
    //    NSURL* url=  [NSURL URLWithString:@"https://www.apple.com"];haomagege20k
    [[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@---%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],error);
    }] resume];
}


#pragma mark ----------------------
#pragma mark NSURLSessionDataDelegate
/*
 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 = 0,  使用这个证书
     NSURLSessionAuthChallengePerformDefaultHandling = 1,  默认的处理  忽略                         /*
     NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2,会取消请求,忽略
     NSURLSessionAuthChallengeRejectProtectionSpace = 3,  拒绝,以后再次询问
     */
    NSURLCredential  *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    
    //第一个参数:如何处理这个证书(质询)
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    
}

AFN

-(void)afn
{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURL* url=  [NSURL URLWithString:@"https://kyfw.12306.cn/otn/"];
    
    //设置解析方式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.securityPolicy.allowInvalidCertificates = YES;//是否允许过期的证书
    manager.securityPolicy.validatesDomainName = NO;//是否域名验证
    
    [[manager dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        NSLog(@"%@---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding],error);
    }] resume];
}
posted @ 2017-03-24 11:33  漫天要价  阅读(229)  评论(0编辑  收藏  举报