没有办法绕过那个 SSL 验证方案,经过一段时间的尝试和到处寻找解决方案后,我不得不实现一个类来做到这一点。
由于 NSString 的 stringWithContentsOfURL 的优势是同步的,我必须确保我的也是同步的。对于每个目的,它可能有点大,但你明白了它的要点。
@interface NZStringLoader : NSObject
@property (assign, readonly, nonatomic) BOOL done;
@property (strong, readonly, nonatomic) NSString *result;
@property (strong, readonly, nonatomic) NSURLConnection *conn;
- (id) initWithURL:(NSURL*)u;
- (void) loadSynchronously;
@end
@implementation NZStringLoader
@synthesize done = _done, result = _result, conn = _connection;
- (id) initWithURL:(NSURL*)u {
NSURLRequest *req = [[NSURLRequest alloc] initWithURL:u
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10.0];
_connection = [NSURLConnection connectionWithRequest:req delegate:self];
_done = NO;
return self;
}
- (void) loadSynchronously {
[_connection start];
while(!_done)
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:.15]];
}
#pragma mark -
#pragma mark NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
_done = YES;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
RTLog(@"%@", [error localizedDescription]);
_done = YES;
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if(_result == nil)
_result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
else
_result = [_result stringByAppendingString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
}
@end
它是这样使用的:
NZStringLoader *sl = [[NSStringLoader alloc] initWithURL:u];
[sl loadSynchronously];
result = sl.result;
如果我愿意,我想我可以只打一个电话。