本文主要是介绍iOS - HTTPS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、简介
- HTTPS
即 HTTP + SSL 层,具体介绍在这里。 - 关于 iOS HTTPS 应该是大多数人想要的
二、HTTPS与HTTP的区别
- 这里用两张图来介绍两者的区别:
- HTTP:当客户端发送请求,那么服务器会直接返回数据。
HTTP.png
- HTTPS:当客户端第一次发送请求的时候,服务器会返回一个包含公钥的受保护空间(也成为证书),当我们发送请求的时候,公钥会将请求加密再发送给服务器,服务器接到请求之后,用自带的私钥进行解密,如果正确再返回数据。这就是 HTTPS 的安全性所在。
-
HTTPS.png
-
三、实例
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDataDelegate>
@end
@implementation ViewController- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{NSURL *url = [NSURL URLWithString:@"https://kyfw.12306.cn/otn/leftTicket/init"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];NSURLSessionDataTask *task = [session dataTaskWithRequest:request];[task resume];
}
#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challengecompletionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))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);}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{NSLog(@"didReceiveResponse");completionHandler(NSURLSessionResponseAllow);
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{NSLog(@"didReceiveData");
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{NSLog(@"didCompleteWithError");
}
@end
四、问题
- 有时采用HTTPS 无法接受数据,是因为苹果将http使用的是TLS 1.2 SSL 加密请求数据,而服务器有的时候使用的还是TLS 1.1
- 解决办法:在 info.plist 中添加
- <key>NSAppTransportSecurity</key><dict>
<key>NSAllowsArbitraryLoads</key>
<true/></dict>
打造安全的 APP HTTPS
这篇关于iOS - HTTPS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!