欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AFNetworking、ASIHTTPRequest中SSL的使用

程序员文章站 2023-02-28 21:45:58
首先介绍下afnetworking中的使用: 2.0要注意个地方:ios7及其以后,采用afhttpsessionmanager,ios7之前采用afhttprequestoperationmana...

首先介绍下afnetworking中的使用:

2.0要注意个地方:ios7及其以后,采用afhttpsessionmanager,ios7之前采用afhttprequestoperationmanager。

以afhttpsessionmanager为例,代码如下:

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:@https://xxxx parameters:nil success:^(nsurlsessiondatatask *task, id responseobject) {
        
    } failure:^(nsurlsessiondatatask *task, nserror *error) {
        //失败信息
    }];

以afhttprequestoperationmanager为例,代码如下:
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:@https://xxxx parameters:nil success:^(afhttprequestoperation *operation, id responseobject) {
        //成功信息
    } failure:^(afhttprequestoperation *operation, nserror *error) {
        //失败信息
    }];


下面来讲下asi,

以asiformdatarequest为例,代码如下:

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];



asihttprequest的参考https://www.tuicool.com/articles/un3aver,代码就不贴了。