HTTPS
- 发送请求之前先挑战服务器(进行
https
的协商)
https的协商
- 信任服务器返回的证书(公钥)
- 客户端产生随机秘钥
- 公钥对随机秘钥进行对称加密
rsa
- 把用公钥加密后的随机秘钥发送给服务器
- 使用随机秘钥加密数据和服务器交互
#pragma mark - 懒加载
-(NSURLSession *)session{
if (_session == nil) {
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
#pragma mark - 代理方法
//挑战
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{
//判断是认证方式(用户名密码,还是证书认证)
if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust){
//设置信任服务器的证书
NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
completionHandler(0,credential);
}
}
NSURLSessionConfiguration
NSURLSessionConfiguration
作用
- 可以设置请求头(
Content-type Range User-agent Authorization
等) - 可以设置最大连接数
- 可以设置超时时长,缓存策略
类方法,创建对象
defaultSessionConfiguration
会使用磁盘缓存,账户信息存储到钥匙链,如果有cookie
会携带cookie
ephemeralSessionConfiguration
没有磁盘缓存,不存储账户信息,不携带cookie
数据存储在内存,速度快,如果要存储到磁盘需要自己写backgroundSessionConfigurationWithIdentifier
在一个单独的进程上下载
属性app进入后台或终止之后,依然可以继续下载- 属性
HTTPAdditionalHeaders
:添加请求头,可以设置账号密码
requestCachePolicy
:缓存策略
timeoutIntervalForRequest
:请求的超时时长
allowsCellularAccess
:运行蜂窝网络访
HTTPMaximumConnectionsPerHost
:主机的最大连接数