iOS 之如何用AF进行网络请求(https)

在开发的时候我们很多时候都要用到https,现在我主要用都请求方式有两种,一种是不校验证书(不需要导入.cer文件),这种比较简单。

在Info.plist中添加NSAppTransportSecurity类型Dictionary。

在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES

1.不需要导入证书

.h文件

@interface ZRNetWork :NSObject

@property(nonatomic,strong)AFHTTPSessionManager*manager;

+(instancetype)shareInstance;

.m文件

staticZRNetWork*network;

+(instancetype)shareInstance{

staticdispatch_once_tonceToken;

dispatch_once(&onceToken, ^{

network=[[ZRNetWorkalloc]init];

[networksetManager];

});

returnnetwork;

}

-(void)setManager{

_manager= [AFHTTPSessionManagermanager];

//AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];

AFSecurityPolicy*securityPolicy = [AFSecurityPolicypolicyWithPinningMode:AFSSLPinningModeCertificate];

//allowInvalidCertificates是否允许无效证书(也就是自建的证书),默认为NO//如果是需要验证自建证书,需要设置为YES

securityPolicy.allowInvalidCertificates=YES;

//validatesDomainName是否需要验证域名,默认为YES;

securityPolicy.validatesDomainName=NO;

[_manager.requestSerializerwillChangeValueForKey:@"timeoutinterval"];

_manager.requestSerializer.timeoutInterval=20.f;

[_manager.requestSerializerdidChangeValueForKey:@"timeoutinterval"];

_manager.securityPolicy= securityPolicy;

_manager.responseSerializer= [AFHTTPResponseSerializerserializer];

}

然后封装网络请求(测试)就可以了

-(void)rquestWithTestSuccess:(ZRBlock)block{

[selfPOSTWithHOST:Request_URL_Testparameters:nilshow:YESblock:^(idobj) {

block(obj);

}];

}

2.需要导入.cer证书,(在阿里云服务器中下载证书,里面有几个证书,但是主要用到都是publick.pem)

openssl x509 -in 下载的publick.pem -out 想要的名字.cer -outform der(不转化使用的时候会报错)

_manager= [AFHTTPSessionManagermanager];

//AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];

AFSecurityPolicy*securityPolicy = [AFSecurityPolicypolicyWithPinningMode:AFSSLPinningModeCertificate];

//allowInvalidCertificates是否允许无效证书(也就是自建的证书),默认为NO//如果是需要验证自建证书,需要设置为YES

securityPolicy.allowInvalidCertificates=YES;

//validatesDomainName是否需要验证域名,默认为YES;

securityPolicy.validatesDomainName=NO;

[_manager.requestSerializerwillChangeValueForKey:@"timeoutinterval"];

_manager.requestSerializer.timeoutInterval=20.f;

[_manager.requestSerializerdidChangeValueForKey:@"timeoutinterval"];

_manager.securityPolicy= securityPolicy;

_manager.responseSerializer= [AFHTTPResponseSerializerserializer];

[selfsetSecerityCertificater];



//设置证书

-(void)setSecerityCertificater{

__weaktypeof(self) weakSelf =self;

[_managersetSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session,NSURLAuthenticationChallenge*challenge,NSURLCredential*__autoreleasing*_credential) {

SecTrustRefserverTrust = [[challengeprotectionSpace]serverTrust];

/**

*导入多张CA证书   zbc需要替换成你证书的名字

*/

NSString*cerPath = [[NSBundlemainBundle]pathForResource:@"zbc"ofType:@"cer"];//自签名证书

//NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"public" ofType:@"pem"];//自签名证书

//NSString *cerPath2 = [[NSBundle mainBundle] pathForResource:@"public" ofType:@"cer"];//自签名证书

NSData* caCert = [NSDatadataWithContentsOfFile:cerPath];

//NSArray *cerArray = @[caCert];

NSSet*cerArray = [[NSSetalloc]initWithObjects:caCert,nil];

weakSelf.manager.securityPolicy.pinnedCertificates= cerArray;

SecCertificateRefcaRef =SecCertificateCreateWithData(NULL, (__bridgeCFDataRef)caCert);

NSCAssert(caRef !=nil,@"caRef is nil");

NSArray*caArray =@[(__bridgeid)(caRef)];

NSCAssert(caArray !=nil,@"caArray is nil");

OSStatusstatus =SecTrustSetAnchorCertificates(serverTrust, (__bridgeCFArrayRef)caArray);

SecTrustSetAnchorCertificatesOnly(serverTrust,NO);

NSCAssert(errSecSuccess == status,@"SecTrustSetAnchorCertificates failed");

NSURLSessionAuthChallengeDispositiondisposition =NSURLSessionAuthChallengePerformDefaultHandling;

__autoreleasingNSURLCredential*credential =nil;

if([challenge.protectionSpace.authenticationMethodisEqualToString:NSURLAuthenticationMethodServerTrust]) {

if([weakSelf.manager.securityPolicyevaluateServerTrust:challenge.protectionSpace.serverTrustforDomain:challenge.protectionSpace.host]) {

credential = [NSURLCredentialcredentialForTrust:challenge.protectionSpace.serverTrust];

if(credential) {

disposition =NSURLSessionAuthChallengeUseCredential;

}else{

disposition =NSURLSessionAuthChallengePerformDefaultHandling;

}

}else{

disposition =NSURLSessionAuthChallengeCancelAuthenticationChallenge;

}

}else{

disposition =NSURLSessionAuthChallengePerformDefaultHandling;

}

returndisposition;

}];

}


到此,基本可以了

你可能感兴趣的:(iOS 之如何用AF进行网络请求(https))