iOS NSURLConnection 和 AfNetworking免证书https连接

  1. NSURLConnection

  1.1  首先添加代理 

    //uiViewController.h
    <NSURLConnectionDelegate,NSURLConnectionDataDelegate,NSURLConnectionDownloadDelegate>

   是不是全部需要三个我也没有具体细究,反正全加上去就行了。



1.2在.m文件里面实现下面连个代理方法,代码不需要更改任何地方,这是用来配置免证书的。

//uiViewController.m
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] ==0){
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
    }else{
        [[challenge sender]cancelAuthenticationChallenge:challenge];
    }
}

  1.3接下来以源码形式打开info.plist 添加如下代码:

<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSExceptionDomains</key>
		<dict>
			<key>baidu.com</key>
			<dict>
				<key>NSIncludesSubdomains</key>
				<true/>
				<key>NSExceptionRequiresForwardSecurity</key>
				<false/>
				<key>NSExceptionAllowsInsecureHTTPLoads</key>
				<true/>
			</dict>
		</dict>
	</dict>

因为iOS对于https的加密算法有强度要求。在这里可以对指定的域名进行例外设置。使用的时候只需要把“baidu.com”换成自己服务器的域名就行了。

1.4然后就可以使用NSURLConnection了:

//uiViewController.m
    /**
     *  1. 在 info.plist 文件里打开App Transport Security Settings
     *  2. 再打开 Exception Domains
     *  3. 将里面的baidu.com换成自己服务器的domian就可以了
     *
     *  
     */
     //    1.设置请求路径
         NSString *urlStr=[NSString stringWithFormat:@"https://www.baidu.com"];
         NSURL *url=[NSURL URLWithString:urlStr];
     //    2.创建请求对象
         NSURLRequest *request=[NSURLRequest requestWithURL:url];
     //    3.发送请求
         //发送同步请求,在主线程执行
    [NSURLConnection connectionWithRequest:request delegate:self];

1.5之后还需要实现几个用来监听状态及接收数据的代理方法:

//uiViewController.m
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"error:%@",error);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"--->%@",response.accessibilityValue);
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
    NSLog(@"____>%@",result);
}

这样就可以使用https连接服务器了。


2.AFNetworking

这是个很通用的第三方网路连接库,很多人都在使用,如果这个不能连接https那简直太坑爹了。作为一个牛逼的网络链库,它肯定是对https有支持的,但是想使用却得经过一番配置,只是这个配置要比NSURLConnection简单太多了。

2.1 同样的要尽行步骤1.3的配置。

2.2配置使用默认安全协议。

 // 1.请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    mgr.securityPolicy = securityPolicy;

2.3创建网络连接

[mgr GET:@"https://baidu.com" parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        NSLog(@"%@",responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败-%@", error);
    }];

作为牛逼中的大牛逼,AFNetworking配置起来是不是简单太多了。

demo地址:http://git.oschina.net/liaojinghui/HTTPS_TEST

OK,这样就可以爽快的跟测试妹纸~~~我说聊天。

你可能感兴趣的:(iOS NSURLConnection 和 AfNetworking免证书https连接)