使用NSURLSession发起HTTPS网络请求

来源:互联网 发布:pi补偿网络的设计 编辑:程序博客网 时间:2024/05/16 11:37
 最近需要发送https请求,所以就封装了一个使用NSURLSession发起HTTPS请求的类,以post请求为例看代码。 首先在.h文件中会暴露出一个对象方法,用于发起post请求:
   - (void)postRequstUrl:(NSString *)url andJsonParam:(NSString *)jsonParam; 

然后会有一个代理用于接受网络请求的结果:

@protocol FWHttpsDelegate <NSObject>/** https请求的结果 */- (void)postResponesData:(NSData *)data andUrlRespones:(NSURLResponse *) response andError:(NSError *)error;@end

代理属性:

@property (nonatomic,weak)id<FWHttpsDelegate> delegateHttps;

再看具体的实现:
第一步,你需要一个请求类Request,并设置Request的属性:

  NSMutableURLRequest * requst = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];    //延时时间    requst.timeoutInterval = self.timeOut > 0? self.timeOut:30;    //请求方式    requst.HTTPMethod = @"POST";    NSData *data = [jsonParam dataUsingEncoding:NSUTF8StringEncoding];    //请求体    requst.HTTPBody = data;

第二步,你要创建一个存储配置:

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

第三步,通信会话NSURLSession,你最好用NSURLSessionConfiguration,代理,线程来创建一个NSURLSession

 NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];

第四步,使用session,requst来创建个任务NSURLSessionDataTask:

 NSURLSessionDataTask *task = [session dataTaskWithRequest:requst completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {        if ([self.delegateHttps respondsToSelector:@selector(postResponesData:andUrlRespones:andError:)]) {            [self.delegateHttps postResponesData:data andUrlRespones:response andError:error];        }    }];

最后不要忘了要开始任务:

 [task resume];

好了,到了这里就是一个最简单的使用NSURLSession发起的post网络请求了,但是这个明显跟HTTPS无关,不要急下面我们就来实现个代理让我们可以发起HTTPS请求。

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler

我自己测试过,很神奇的是这个代理只有当你请求的网络地址是https的时候才会调用,所以简单了我们可以实现这个代理用来处理https网络请求:
先认识几个枚举值,
NSURLSessionAuthChallengeUseCredential 使用证书
NSURLSessionAuthChallengePerformDefaultHandling 忽略证书 默认的做法
NSURLSessionAuthChallengeCancelAuthenticationChallenge 取消请求,忽略证书
NSURLSessionAuthChallengeRejectProtectionSpace 拒绝,忽略证书
简单的思路是,如果有证书就使用证书,没有证书就忽略证书,不多说了看代码:

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {    //证书的处理方式    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;    //网络请求证书    __block NSURLCredential *credential = nil;    //判断服务器返回的证书是否是服务器信任的    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { //受信任的       //获取服务器返回的证书        credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];        if (credential) {            disposition = NSURLSessionAuthChallengeUseCredential;        } else {            disposition = NSURLSessionAuthChallengePerformDefaultHandling;        }    } else {        disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;    }    //安装证书    if (completionHandler) {        completionHandler(disposition, credential);    }}
0 0
原创粉丝点击