具体使用
代理(不使用框架)
1.确定URL
NSURL *url = [NSURL URLWithString:@"https://......"];
2.创建请求对象
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
3.创建会话对象(自定义),设置代理
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
4.创建Task
NSURLSessionDownloadTask *downTask = [session downloadTaskWithRequest:request];
5.执行Task
[downTask resume];
实现代理方法
// https请求时,安装证书,否则https请求不会成功(代理方法安装)
// challenge 质询,挑战(弹出来的一个框,提示我们是否需要安装这个证书)
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
//我们进行判断一下,是否是服务器信任,如果是,我们将安装证书以及授权信息
if ([challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
//NSURLSessionAuthChallengeDisposition 如何处理证书
/*
NSURLSessionAuthChallengeUseCredential = 0, 使用该证书,安装该证书
NSURLSessionAuthChallengePerformDefaultHandling = 1, 默认采用的方式,该证书被忽略
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 取消请求,证书忽略
NSURLSessionAuthChallengeRejectProtectionSpace = 3, 拒绝
*/
//NSURLCredential 授权信息(服务信任)
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust: challenge.protectionSpace.serverTrust];
//传给系统一个block
completionHandler(NSURLSessionAuthChallengeUseCredential , credential);
}
框架(AFN)
- 创建文件管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
- 更改解析方式
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
- 对证书的处理方式(YES:接收无效的证书,非购买的证书被认为是无效的证书)
manager.securityPolicy.allowInvalidCertificates = YES;
无效的证书我们还需要关闭域名认证
manager.securityPolicy.validatesDomainName = NO;
- 发送GET请求
[manager GET:@"https://...." parameters:paramDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//返回的数据是二进制类型,我们将他转换成字符串
NSLog(@"%@" , [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
<#code#>
}];