文艺求关注.png
- 如何使用session发送HTTPS请求(需使用代理方法)
- (void)session {
// 1.确定URL
NSURL *url = [NSURL URLWithString:@"https://www.12306.cn/mormhweb/"];
// 2.设置请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.创建会话对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// 4.创建Task
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 6.解析数据
NSLog(@"-- %@ ------- %@ ---", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding], error);
}];
// 5.执行Task
[dataTask resume];
}
// 代理协议
<NSURLSessionDataDelegate>
#pragma mark - NSURLSessionDataDelegate
/**
// 如果发送的请求是HTTPS的请求,该方法才会被调用
@param session 会话对象
@param challenge 质询,挑战
@param completionHandler 回调
*/
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
return;
}
NSLog(@"%@", challenge.protectionSpace);
// NSURLSessionAuthChallengeDisposition 如何处理证书
/**
NSURLSessionAuthChallengeUseCredential = 0, 安装并使用该证书
NSURLSessionAuthChallengePerformDefaultHandling = 1, 默认方式,该证书会被忽略
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 取消请求,忽略证书
NSURLSessionAuthChallengeRejectProtectionSpace = 3, 拒绝
*/
// NSURLCredential 授权信息
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
- 一般在开发中一般会使用第三方框架处理发送网络数据,我们以AFNetworking为例讲
- (void)AFN {
// 01.创建会话管理对象
AFHTTPSessionManager *httpSessionManager = [AFHTTPSessionManager manager];
// +// 更改解析方式
httpSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
// +// 设置对证书的处理方式 是否接收无效证书
httpSessionManager.securityPolicy.allowInvalidCertificates = YES;
// +// AFN内部默认会对域名进行验证 修改是否对域名进行验证
httpSessionManager.securityPolicy.validatesDomainName = NO;
// 02.发送请求
[httpSessionManager GET:@"https://www.12306.cn/mormhweb/" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"-- %@ ---", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"-- %@ ---", error);
}];
}
关注一下又不会怀孕.png
网友评论