本文主要是介绍iOS HTTPS证书不受信任解决办法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
之前开发App的时候服务端使用的是自签名的证书,导致iOS开发过程中调用HTTPS接口时,证书不被信任
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{/*方法一*/if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];if(completionHandler)completionHandler(NSURLSessionAuthChallengeUseCredential,credential);}/*方法二*/
// SecTrustRef servertrust = challenge.protectionSpace.serverTrust;
// SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);
// NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));
// NSString *path = [[NSBundle mainBundle] pathForResource:@"证书名称" ofType:@"cer"];NSLog(@"证书 : %@",path);
// NSData *localCertiData = [NSData dataWithContentsOfFile:path];
// if ([certidata isEqualToData:localCertiData]) {
// NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];
// [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
// completionHandler(NSURLSessionAuthChallengeUseCredential, credential);NSLog(@"服务端证书认证通过");
// }else {
// completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
// NSLog(@"服务端认证失败");
// }}
这里有两个方法,第一个是信任所有证书,第二个是把服务端自签名的证书放到本地,类似白名单的样子去加载
源码
HttpRequest.h
//
// HttpRequest.h
//
// Created by Michael Zhan on 2017/5/17.
// Copyright © 2017年 Michael Zhan. All rights reserved.
//#import <Foundation/Foundation.h>static NSString * const baseUrl = @"http://";typedef void (^SuccessBlock)(NSString * data);
typedef void (^FailureBlock)(NSError * error);@interface HttpRequest : NSObject <NSURLSessionTaskDelegate>- (void)getWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)postWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)getWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)postWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)postWithDict2String:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;@end
HttpRequest.m
//
// HttpRequest.m
//
// Created by Michael Zhan on 2017/5/17.
// Copyright © 2017年 Michael Zhan. All rights reserved.
//#import "HttpRequest.h"@implementation HttpRequest- (void)getWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSMutableString * mutableStringUrl = [[NSMutableString alloc] initWithString:paramUrl];[mutableStringUrl appendString:[HttpRequest convertToJsonData:paramDicet]];NSLog(@"url %@",mutableStringUrl);NSURL * url = [NSURL URLWithString:[mutableStringUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);}}];[dataTask resume];}- (void)postWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSURL * url = [NSURL URLWithString:paramUrl];NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];request.HTTPMethod = @"POST";NSString * jsonStr = [HttpRequest convertToJsonData:paramDicet];request.HTTPBody = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];
}- (void)postWithDict2String:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSURL * url = [NSURL URLWithString:paramUrl];NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];request.HTTPMethod = @"POST";NSString * jsonStr = [NSString stringWithFormat:@"%@",paramDicet];request.HTTPBody = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];request.timeoutInterval = 10;request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];
}- (void)getWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSMutableString * mutableStringUrl = [[NSMutableString alloc] initWithString:paramUrl];[mutableStringUrl appendString:paramString];NSLog(@"url %@",mutableStringUrl);NSURL * url =[NSURL URLWithString:[mutableStringUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];}- (void)postWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSURL * url = [NSURL URLWithString:paramUrl];NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];request.HTTPMethod = @"POST";request.HTTPBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];request.timeoutInterval = 10;request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];
}+ (NSString *)convertToJsonData:(NSDictionary *)dict{NSError *error;NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];NSString *jsonString;if (!jsonData) {NSLog(@"%@",error);}else{jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];}NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];NSRange range = {0,jsonString.length};//去掉字符串中的空格[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];NSRange range2 = {0,mutStr.length};//去掉字符串中的换行符[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];return mutStr;
}- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{/*方法一*/if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];if(completionHandler)completionHandler(NSURLSessionAuthChallengeUseCredential,credential);}/*方法二*/
// SecTrustRef servertrust = challenge.protectionSpace.serverTrust;
// SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);
// NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));
// NSString *path = [[NSBundle mainBundle] pathForResource:@"zwp" ofType:@"cer"];NSLog(@"证书 : %@",path);
// NSData *localCertiData = [NSData dataWithContentsOfFile:path];
// if ([certidata isEqualToData:localCertiData]) {
// NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];
// [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
// completionHandler(NSURLSessionAuthChallengeUseCredential, credential);NSLog(@"服务端证书认证通过");
// }else {
// completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
// NSLog(@"服务端认证失败");
// }}@end
这篇关于iOS HTTPS证书不受信任解决办法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!