錯誤:“此服務器的證書無效。您可能正在連接到一個偽裝成“www.xxxxxx.com”的服務器思犁, 這會威脅到您的機密信息的安全
原因:安全證書是自己的服務器生成的,未獲權威認證进肯,即沒有正式的域名激蹲。
1、此處創(chuàng)建session對象時坷澡,必須用此方法創(chuàng)建托呕,可以設置代理。因為代理NSUrlSessionDelegate是只讀的频敛,不能單獨設置项郊,所以必須創(chuàng)建時設置。
Paste_Image.png
- (void)dataTaskJasonSendDict
{
NSURL *url=[NSURL URLWithString:@"https://192.168.1.42/siweb/iface/user/checkLogin"];
// 創(chuàng)建請求request斟赚,設置請求頭內(nèi)容
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
request.HTTPMethod=@"POST";
// 此處發(fā)送一定要設置着降,這個地方把字典封裝為json格式
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:@"aa123456" forKey:@"username"];
[params setObject:@"aa123456" forKey:@"password"];
// 將可變字典轉化為二進制數(shù)據(jù)
NSData *data=[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody=data;
[request setHTTPShouldHandleCookies:YES];
NSURLSession *session=[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// 返回的為json,解析
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if (dict[@"error"]) {
NSLog(@"%@",dict[@"error"]);
}
else
{
NSLog(@"%@",dict[@"success"]);
}
}];
[dataTask resume];
}
2拗军、每次請求時都會調(diào)用以下的代理方法任洞,判斷是否證書是否被服務器信任。
Paste_Image.png
將其設置為這樣发侵,就能強制信任交掏,可以進行正常請求。
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential , card);
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
// NSLog(@"didReceiveChallenge %@", challenge.protectionSpace);
NSLog(@"調(diào)用了最外層");
// 1.判斷服務器返回的證書類型, 是否是服務器信任
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSLog(@"調(diào)用了里面這一層是服務器信任的證書");
/*
NSURLSessionAuthChallengeUseCredential = 0, 使用證書
NSURLSessionAuthChallengePerformDefaultHandling = 1, 忽略證書(默認的處理方式)
NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 忽略書證, 并取消這次請求
NSURLSessionAuthChallengeRejectProtectionSpace = 3, 拒絕當前這一次, 下一次再詢問
*/
// NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential , card);
}
}