AFNetworking、ASIHTTPRequest中SSL的使用

首先介紹下AFNetworking中的使用:html

2.0要注意個地方:IOS7及其之後,採用AFHTTPSessionManagerIOS7以前採用AFHTTPRequestOperationManagerpost

AFHTTPSessionManager爲例,代碼例如如下:ui

<span style="font-size:14px;">AFHTTPSessionManager   *httpClient = [AFHTTPSessionManager manager];
    httpClient.requestSerializer = [AFHTTPRequestSerializer serializer];
    httpClient.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // SSL Pinning
    NSString *certificatePath = [[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"der"];
    NSData *certificateData = [NSData dataWithContentsOfFile:certificatePath];
    
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    [securityPolicy setPinnedCertificates:@[certificateData]];
    [securityPolicy setSSLPinningMode:AFSSLPinningModeCertificate];
    
    [httpClient setSecurityPolicy:securityPolicy];
    
    [httpClient GET:@"http://xxxx" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //失敗信息
    }];</span>

AFHTTPRequestOperationManager爲例,代碼例如如下:
<span style="font-size:14px;">AFHTTPRequestOperationManager *httpClient1 = [AFHTTPRequestOperationManager manager];
    httpClient1.requestSerializer = [AFHTTPRequestSerializer serializer];
    httpClient1.responseSerializer = [AFHTTPResponseSerializer serializer];
    // SSL Pinning
    NSString *certificatePath1 = [[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"der"];
    NSData *certificateData1 = [NSData dataWithContentsOfFile:certificatePath1];
    
    AFSecurityPolicy *securityPolicy1 = [[AFSecurityPolicy alloc] init];
    [securityPolicy1 setAllowInvalidCertificates:YES];
    [securityPolicy1 setPinnedCertificates:@[certificateData1]];
    [securityPolicy1 setSSLPinningMode:AFSSLPinningModeCertificate];
    
    [httpClient setSecurityPolicy:securityPolicy1];
    
    [httpClient1 GET:@"http://xxxx" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //成功信息
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //失敗信息
    }];</span>


如下來說下ASI,

ASIFormDataRequest爲例。代碼例如如下:spa

<span style="font-size:14px;">ASIFormDataRequest * request;
    request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@""]];
    NSData *cerFile = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"d1" ofType:@"cer"]];
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)cerFile);
    NSArray *array = [NSArray arrayWithObjects:(__bridge id)cert,nil];
    [request setClientCertificates:array];
    [request setValidatesSecureCertificate:NO];
    
    [request startSynchronous];</span>



ASIHTTPRequest的參考http://www.tuicool.com/articles/UN3AveR。代碼就不貼了。

http://blog.iamzsx.me/show.html?

id=155002
.net

相關文章
相關標籤/搜索