Sloppy's Blog

IOS NSURLConnect忽略HTTPS不被认证的证书访问

背景

最近由于IOS需要HTTPS的协议,公司所有的HTTP协议全部改成HTTPS了,可是本地的DEBUG测试环境。是自己创建的HTTPS证书。不是被认证机构认证的。而IOS通信中的NSURLConnection如果是不被认证的证书,会通信失败。这里为了,兼容DEBUG环境下,需要在DEBUG环境忽略相关的URL接口,需要在通信的时候,实现NSURLConnectionDelegate,需要实现几个方法,如下:

- (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])
        if ([trustedHosts containsObject:challenge.protectionSpace.host])
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
    NSLog(@"response length=%lld statecode%ld", [response expectedContentLength],(long)responseCode);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (mData == nil) {
        mData = [[NSMutableData alloc] initWithData:data];
    } else {
        [mData appendData:data];
    }
    NSString* aStr=[[NSString alloc ]initWithData:mData encoding:NSUTF8StringEncoding];
    NSLog(@"response connection%@",aStr);
    NSLog(@"response connection");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"connectionDidFinishLoading connection");
    if(mData!=nil){
        [mData release];
        mData = nil;
    }
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"connection didFailWithError:%@",error);
}

这里作下说明:trustedHosts是一个NSArray,可以初始下一下:trustedHosts = [[NSArray alloc] initWithObjects:@”10.10.10.160”, nil];,其中的地址就是需要忽略证书的域名或者IP

我这里写了一个简单的测试例子,源码下载:http://www.nikoer.com/data/NSURLConnectionTest.zip

简单调用:[[ErayInterface getInstance] connnect:@”https://10.10.10.160:8080/off/user_charge“];