目前很多APP都要求支持Https通讯,现在大多APP都是AFN框架之上实现的网络通讯层。以下讨论了一下,AFN 框架之下,如何实现Http 和 Https兼容(都支持)。(这个知识点虽然不难,但是网上很少有一试就能成功的帖子)
现在网上有很多“iOS9与XCode7中不能使用http连接的解决办法”的贴子, 做法如下:
- 在项目左侧找到Info.plist文件,可以通过Filter来搜索
- 在右侧点击Add Row添加NSAppTransportSecurity,类型为Dictionary,然后再添加子项目NSAllowsArbitraryLoads类行为 Boolean值为YES
按照以上的操作,的确实现了http的支持。但是如果是通过第三方机构生成SSL数字证书比如https://www.wosign.com/;要实现http,https在AFN构架下同时兼容还不行。(网上有一些通过生成证书,放在App里,实现https的通讯,个人不建议使用此用方案,因为AFN的官网上,指出了修改info.plist文件来实现https通讯。个人按照生成证书,调试AFN框架下的Https通讯,并没有成功)
建议直接用文本工作,打开Info.plist这个xml文件。直接配置如下图信息:
解释一下:
1> IOS9下,对http通讯支持需要添加:
<key>NSAllowsArbitraryLoads</key>
<true/>
2> 如果域名是www.baidu.com的接口,在AFN框架下,要支持https访问,需要添加:
<key>NSExceptionDomains</key>
<dict>
<key>www.baidu.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.2</string>
</dict>
</dict>
如果Https通信中,SSL数字证书是自己生成的AFN示例代码如下
-(void)httpsForPrivateCer {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
// 是否允许,NO-- 不允许无效的证书
[securityPolicy setAllowInvalidCertificates:YES];
[securityPolicy setValidatesDomainName:NO];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval = 20;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.securityPolicy = securityPolicy;
[manager GET:URL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
NSString *result = [[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error come here");
}];
}
如果是通过第三方机构生成SSL数字证书比如
-(void)httpsForPublicCer {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
// 是否允许,NO-- 不允许无效的证书
[securityPolicy setAllowInvalidCertificates:YES];
[securityPolicy setValidatesDomainName:NO];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval = 20;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.securityPolicy = securityPolicy;
[manager POST:@"https://www.baidu.com/home/subscribe/data/manlotteryuserdata?indextype=manht&_req_seqid=0x933251bb0002c2f5&asyn=1&t=1458805039282&sid=18880_18285_1426_17943_18205_17000_15718_12187" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
NSString *result =[[ NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error come here");
}];
}
网友评论