使用NSURLSession网络请求的https配置

https请求配置方法,以下是微信授权请求

- (void)getRequestWithAFNewWorkWithUrl:(NSString *)url
                               success:(void(^)(NSDictionary *resultDic))success
                               failure:(void(^)(NSString *error,int errorCode))failure
{
    if (url.length == 0) {
        return;
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        //https 需要配置证书
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.timeoutIntervalForRequest = 20;
        
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
        
        
        NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
           
            if (error == nil) {
                
                if (![data isKindOfClass:[NSData class]]) {
                    return ;
                }
                
                NSString *responseObjStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                
                NSString *dataStr = [DataSend ReplacingNewLineAndWhitespaceCharactersFromJson:responseObjStr];
                NSError *error;
                NSData *response = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    success(resultDic);
                });
                
            } else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    NSLog(@"服务器挂了~~~^_^%@",url);
                    
                    failure(@"网络请求错误~~", (int)error.code);

                });
            }
        }];
        
        [task resume];
        
    });
}

获取证书的代理

#pragma mark - NSURLSessionDelegate

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
    {
        //服务器信任证书
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];//服务器信任证书
        if (completionHandler) {
            completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
        }
    }
}

你可能感兴趣的:(使用NSURLSession网络请求的https配置)