Error Domain=NSURLErrorDomain Co
2016-12-09 本文已影响2306人
RM_乾笙
错误:“此服务器的证书无效。您可能正在连接到一个伪装成“www.xxxxxx.com”的服务器, 这会威胁到您的机密信息的安全
原因:安全证书是自己的服务器生成的,未获权威认证,即没有正式的域名。
1、此处创建session对象时,必须用此方法创建,可以设置代理。因为代理NSUrlSessionDelegate是只读的,不能单独设置,所以必须创建时设置。
Paste_Image.png
- (void)dataTaskJasonSendDict
{
NSURL *url=[NSURL URLWithString:@"https://192.168.1.42/siweb/iface/user/checkLogin"];
// 创建请求request,设置请求头内容
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
request.HTTPMethod=@"POST";
// 此处发送一定要设置,这个地方把字典封装为json格式
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:@"aa123456" forKey:@"username"];
[params setObject:@"aa123456" forKey:@"password"];
// 将可变字典转化为二进制数据
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、每次请求时都会调用以下的代理方法,判断是否证书是否被服务器信任。
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(@"调用了最外层");
// 1.判断服务器返回的证书类型, 是否是服务器信任
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSLog(@"调用了里面这一层是服务器信任的证书");
/*
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);
}
}