美文网首页iOS随笔小记
iOS随笔小记--HTTPS请求

iOS随笔小记--HTTPS请求

作者: 七一小月 | 来源:发表于2017-06-27 10:48 被阅读22次

    将HTTPS请求封装在一个类里面,方便调用(前提是在项目里面要导入AFNetworking第三方库)

    .h文件
    #import
    #import "AFNetworking.h"
    
    @interface YDHTTPSManager : NSObject
    
    /**
    *  发送一个HTTPS的GET请求
    * @param url    请求路径
    * @param params  请求参数
    *  @param success 请求成功后的回调
    *  @param failure 请求失败后的回调
    */
    + (void)GET:(NSString *)URLString parameters:(id)parameters success:(void(^)(id responseObject))sucess failure:(void(^)(NSError *error))failure;
    
    /**
    *  发送一个HTTPS的POST请求
    *  @param url    请求路径
    *  @param params  请求参数
    *  @param success 请求成功后的回调
    *  @param failure 请求失败后的回调
    */
    +(void)post:(NSString *)UrlString params:(NSDictionary *)params success:(void (^)(id json))success failure:(void(^)(NSError *error))failure;
    
    /**
    *  发送一个HTTPS的POST请求(上传图片)
    *  @param url    请求路径
    *  @param params  请求参数
    *  @param success 请求成功后的回调
    *  @param failure 请求失败后的回调
    */
    +(void)post:(NSString *)UrlString params:(NSDictionary *)params formData:(void (^)(idformData))block prodress:(void(^)(NSProgress *uploadProgress))progress  success:(void (^)(id json))success failure:(void(^)(NSError *error))failure;
    
    .m文件
    #import "YDHTTPSManager.h"
    #import "AFNetworking.h"
    
    @implementation YDHTTPSManager
    
    + (void)GET:(NSString *)URLString parameters:(id)parameters success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure{  
    
     AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];   
    
     // 设置网络请求超时时间    
     manger.requestSerializer.timeoutInterval = 10;   
     [manger.securityPolicy setAllowInvalidCertificates:YES];  
    
     // https ssl 验证。  
     [manger setSecurityPolicy:[self customSecurityPolicy]];    
    
     // 请求  
     manger.requestSerializer=[AFJSONRequestSerializer serializer];    
    
     // 响应( 返回格式 )  
     manger.responseSerializer = [AFHTTPResponseSerializer serializer];       
    
     NSString *encoded = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    
    
    [manger GET:encoded parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {            
    
      //如果请求成功的话将responseObject保存在sucess Block中      
    
          if (success)  {        
    
            success(responseObject);    
            }          
    
          } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {    
    
            if(failure)  {   
    
                 failure(error);    
             }        
        }];   
    
     }
    
    
    
    +(void)post:(NSString *)UrlString params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{   
    
     AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];   
    
     // 设置网络请求超时时间    
    manger.requestSerializer.timeoutInterval = 10;   
    
    [manger.securityPolicy setAllowInvalidCertificates:YES];   
    
     // https ssl 验证。   
     [manger setSecurityPolicy:[self customSecurityPolicy]];  
    
      // 请求  
      manger.requestSerializer=[AFJSONRequestSerializer serializer];   
    
     // 响应( 返回格式 ) 
       manger.responseSerializer = [AFHTTPResponseSerializer serializer];    
    
     // NSString *encoded = [URLString     stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];     
    
      [manger POST:UrlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {             
    
       //如果请求成功的话将responseObject保存在sucess Block中    
    
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];     
    
       if (success)        {        
    
            success(result);    
    
        }        
    
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {     
    
              if(failure)        {    
    
            failure(error);      
    
          }        
    
        }];    
    
    }
    
    
    
    +(void)post:(NSString *)UrlString params:(NSDictionary *)params formData:(void (^)(id))block prodress:(void (^)(NSProgress *))progress success:(void (^)(id))success failure:(void (^)(NSError *))failure{   
    
     AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    
    // 设置网络请求超时时间  
    manager.requestSerializer.timeoutInterval = 10;   
    [manager.securityPolicy setAllowInvalidCertificates:YES];   
    
     // https ssl 验证。  
      [manager setSecurityPolicy:[self customSecurityPolicy]];    
    
    // 请求    manager.requestSerializer=[AFJSONRequestSerializer serializer];    
    
    // 响应( 返回格式 )   
     manager.responseSerializer = [AFHTTPResponseSerializer serializer];       
    
     [manager POST:UrlString parameters:params constructingBodyWithBlock:^(id_Nonnull formData) {
    
        if (block) {
    
            block(formData);
    
             }
    
      } progress:^(NSProgress * _Nonnull uploadProgress) {
    
           if (progress) {
    
                 progress(uploadProgress);
    
              }
    
       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
            //如果请求成功的话将responseObject保存在sucess Block中
    
    NSString *result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
    
    if (success){
    
                success(result);
        }
    
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
        if(failure){
    
             failure(error);
    
            }
         }];
    
     }
    
    https ssl 验证。
    //https ssl 验证。
    
    + (AFSecurityPolicy *)customSecurityPolicy {
    
    // 先导入证书 证书由服务端生成
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"wnwHTTPS" ofType:@"cer"];
    
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    //    NSLog(@"cerData = %@",cerData);
    
    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书(也就是自建的证书),默认为NO
    
    // 如果是需要验证自建证书,需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名,默认为YES;
    //假如证书的域名与你请求的域名不一致,需把该项设置为NO;如设成NO的话,即服务器使用其他可信任机构颁发的证书,也可以建立连接,这个非常危险,建议打开。
    
    //置为NO,主要用于这种情况:客户端请求的是子域名,而证书上的是另外一个域名。因为SSL证书上的域名是独立的,假如证书上注册的域名是www.google.com,那么mail.google.com是无法验证通过的;当然,有钱可以注册通配符的域名*.google.com,但这个还是比较贵的。
    
    //如置为NO,建议自己添加对应域名的校验逻辑。
    
    securityPolicy.validatesDomainName = NO;
    
    securityPolicy.pinnedCertificates = [[NSSet alloc] initWithObjects:cerData, nil];
    
    return securityPolicy;
    
    }

    相关文章

      网友评论

        本文标题:iOS随笔小记--HTTPS请求

        本文链接:https://www.haomeiwen.com/subject/gknscxtx.html