记录一下在网络请求中证书验证的基于NSURLConnection的实现
一.开始一个请求
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//保存数据
self.data = [NSMutableData data];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://XXXXXXXXXXXX"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:240];
[request setHTTPMethod:@"POST"];
[request setHTTPShouldHandleCookies:YES];
NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSData *postData = [@"XX=XX&XX=XX" dataUsingEncoding:gbkEncoding];
[request setHTTPBody:postData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
二.实现NSURLConnection验证的回调方法
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
SecTrustRef trust = challenge.protectionSpace.serverTrust;
SecTrustResultType result;
//获取本地证书
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"XXX" ofType:@"cer"]];
SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(data));
SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)@[CFBridgingRelease(certificate)]);
OSStatus status = SecTrustEvaluate(trust, &result);
if (status == errSecSuccess &&
(result == kSecTrustResultProceed ||
result == kSecTrustResultUnspecified)) {
//验证成功,生成NSURLCredential凭证cred,告知challenge的sender使用这个凭证来继续连接
NSURLCredential *cred = [NSURLCredential credentialForTrust:trust];
[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
} else {
//验证失败,取消这次验证流程
[challenge.sender cancelAuthenticationChallenge:challenge];
}
}
}
三.接收数据
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.data appendData:data];
}
四.处理数据
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSString *retStr = [[NSString alloc] initWithData:self.data encoding:enc];
NSLog(@"retString:%@",retStr);
NSData* newData=[retStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id responseObject = [NSJSONSerialization JSONObjectWithData:newData options:NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"error:%@",error);
}
if (responseObject) {
NSLog(@"%@", responseObject);
}else{
}
}