HTTPS请求代码演练

具体使用

代理(不使用框架)

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#>
    }];
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iOS开发疯狂者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值