https請求配置方法,以下是微信授權(quán)請求
- (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(@"服務(wù)器掛了~~~^_^%@",url);
failure(@"網(wǎng)絡(luò)請求錯(cuò)誤~~", (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])
{
//服務(wù)器信任證書
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];//服務(wù)器信任證書
if (completionHandler) {
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
}
}