iOS 关于Https
2016-12-21 本文已影响22人
哔哩哔哩智能喵
-
https和http有哪些不同
-
最关键一点http不安全而https是由SSL + HTTP协议构建的可进行加密传输、身份认证的网络协议,比http安全,并且http端口号是80 https端口号是443.
-
http的握手过程:客户端发送请求给服务器,服务器收到后返回信息给客户端,客户端收到服务器返回的信息完成三次握手
-
https的握手过程(个人理解大概意思):客户端第发送请求给服务器,服务器收到客户端请求的信息(服务器中存有私钥和公钥)后传送公钥给客户端,客户端解析公钥,客户端用公钥产生一个随机值并传送加密后的随机值给服务器,服务器用私钥解密随机值,然后完成通信。
-
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()<NSURLSessionDelegate>
@end
@implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self AFNsendHttps];
}
-(void)AFNsendHttps
{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//是否信任无效或过期的SSL证书
manager.securityPolicy.allowInvalidCertificates = YES;
//是否开启域名验证
manager.securityPolicy.validatesDomainName = NO;
//更改解析方式
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"https://kyfw.12306.cn/otn" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"success---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"error---%@",error);
}];
}
-(void)sendHttps
{
NSURL *url = [NSURL URLWithString:@"https://kyfw.12306.cn/otn"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *datatask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@---%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],error);
}];
[datatask resume];
}
/**
如果发送的请求是https的,那么才会调用该方法
* @param session 会话对象
* @param challenge 询问是否安装SSL证书
* @param completionHandler 传给系统两个参数
NSURLSessionAuthChallengeDisposition :如何处理证书
NSURLSessionAuthChallengeUseCredential = 0, 使用该证书 安装该证书
NSURLSessionAuthChallengePerformDefaultHandling = 1, 默认采用的方式,该证书被忽略
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 取消请求,证书忽略
NSURLSessionAuthChallengeRejectProtectionSpace = 3, 拒绝
NSURLCredential :授权信息
*/
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
//判断一下如果身份验证服务器已经信任的话就return出去
if (![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"]) {
return ;
}
NSURLCredential * credential = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}
@end