iOS开发

iOS AFNetworking

2021-05-17  本文已影响0人  小和大大

http请求

ios10之后访问http请求需要在info.plist中加入字段

image
<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>

AFNetworking结构分析

  1. NSURLConnection

新版本中已经废除

  1. NSURLsession
  1. Reachability:网络状态相关接口
  1. Security:安全性相关的操作接口
  1. Serialization:解析数据相关的操作

• AFURLRequestSerialization

• AFURLResponseSerialization

  1. UIKit:UI界面相关接口

核心模块

image

AFHTTPSessionManager是继承于AFURLSessionManager的,我们一般做网络请求都是用这个类,但是它本身是没有做实事的,只是做了一些简单的封装,把请求逻辑分发给父类AFURLSessionManager或者其它类去做。

AFHTTPSessionManager

Get请求

+(void)getJokeBySort:(NSString *)sort
                page:(int)page
            pageSize:(int)size
                time:(NSString *)time
                 key:(NSString *)key
             success:(void (^)( NSDictionary *resultDic))success
             failure:(void (^)( NSError *error))failure{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    /*
     requestSerializer 上传的参数是什么格式的
     AFHTTPRequestSerializer 普通的http的编码格式,二进制 sort=sort&page=page,默认
     AFJSONRequestSerializerjson 编码格式 "{"sort":"sort","page":"page"}"
     AFPropertyListRequestSerializerplist 编码格式
     */
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];

    /*
     请求超时设置
     */
    manager.requestSerializer.timeoutInterval = 20.f;

    /*
     [AFHTTPResponseSerializer serializer]; 直接使用“服务器本来返回的数据”,不做任何解析
     [AFJSONResponseSerializer serializer]; 解析服务器数据,返回的是JSON数据,默认的
     [AFXMLParserResponseSerializer serializer]; 解析服务器数据,返回的XML数据
     */
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    /*
     如果想在header里加东西的话token/User-Agent/Content-Type
     [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
     */

    NSDictionary *para = @{

        @"sort":sort,
        @"page":[NSNumber numberWithInt:page],
        @"pageSize":[NSNumber numberWithInt:size],
        @"time":time,
        @"key":key
    };

    NSString *url =@"http://v.juhe.cn/joke/content/list.php";

    [manager GET:url parameters:para progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

      NSLog(@"----%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSString *domin = error.domain;

         NSLog(@"+++++%@",domin);

    }];

}

-(void)getJoke{

    [DataManager getJokeBySort:@"desc" page:1 pageSize:10 time:@"1583980251" key:@"640c0f7e1927dc42ca137858a54ed935" success:^(NSDictionary * _Nonnull resultDic) {

    } failure:^(NSError * _Nonnull error) {

    }];
}

Post请求(x-www-form-urlencoded)

+(void)loginUserName:(NSString *)userName
            passWord:(NSString *)password
             Success:(void (^)( NSDictionary *resultDic))success
             failure:(void (^)( NSError* error))failure{

    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.requestSerializer  = [AFHTTPRequestSerializer serializer];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer.timeoutInterval = 20;

    //如果报接受类型(Cntent-Type)不一致请替换text/html
sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    NSString *urlString = @"http://43.248.49.207:7001/HGAuth/api/auth/login";
NSDictionary*parma=@{@"action":@"DO",@"hgflag":userName,@"password":@"96E79218965EB72C92A549DD5A330112"};

    /*
     默认的Content-Type为application/x-www-form-urlencoded,且body中没有参数
     */
    [sessionManager POST:urlString parameters:parma progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];

        NSLog(@"---%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"===%@",error.domain);

    }];

}

-(void)postLogin{

    [DataManager loginUserName:@"lt\\jinguanyd6" passWord:@"111111" Success:^(NSDictionary * _Nonnull resultDic) {

    } failure:^(NSError * _Nonnull error) {

    }];

}

post请求(form-data形式需要上传文件)

+ (void)postImageSuccess:(void(^)(void))success
                 failure:(void(^)(NSError *error))failure{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSString *urlString = @"http://43.248.49.207:8080/HGMMS/appInterface/sendFeedbackImg.html";

    [manager POST:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        UIImage *image = [UIImage imageNamed:@"iceImage"];
        NSData *imageData = UIImageJPEGRepresentation(image,0.2);
        [formData appendPartWithFormData:[@"611" dataUsingEncoding:NSUTF8StringEncoding] name:@"feedbackId"];

        /*
        *该方法的参数
        1\. appendPartWithFileData:要上传的照片[二进制流]
        2\. name:对应网站上[upload.php中]处理文件的字段(比如upload)
        3\. fileName:要保存在服务器上的文件名
        4\. mimeType:上传的文件的类型
        */
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"---------%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"++++++++%@",error.domain);

    }];

}

AFURLSessionManager

post请求body中有参数,可配置Content-type

/*
 post,body中有参数
 */
+(void)cheakNewVisionSuccess:(void (^)( NSDictionary *resultDic))success
                     failure:(void (^)( NSError *error))failure{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

   NSString *URLString = @"http://43.248.49.207:8080/HGMMS/appInterface/checkPortalVersionCdn.html";
   NSURL *url = [NSURL URLWithString:URLString];
   NSURLRequest *request = [NSURLRequest requestWithURL:url];
   NSError *serializationError = nil;
   NSMutableURLRequest *mutaRequest = [[manager.requestSerializer requestBySerializingRequest:request withParameters:nil error:&serializationError] mutableCopy];
   mutaRequest.HTTPMethod = @"POST";

    if (serializationError) {
            if (failure) {
                dispatch_async(manager.completionQueue ?: dispatch_get_main_queue(), ^{
                    failure( serializationError);
                });
            }

            return;
    }

    //设置Content-type为text/html; charset=utf-8,对应postman-body-raw-text/html
    [mutaRequest addValue: @"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //添加body
    NSString*body=@"{\"os\":\"2\"}";
    [mutaRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];

    __block NSURLSessionDataTask *dataTask = nil;

   dataTask = [manager dataTaskWithRequest:mutaRequest uploadProgress:^(NSProgress * _Nonnull uploadProgress) {

    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {

    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        if (error) {
            if (failure) {
                failure(error);
            }
        } else {
            if (success) {
                success(responseObject);
            }
        }
    }];

    [dataTask resume];

}

Content-Type

Content-Type代表发送端(客户端|服务器)发送的实体数据的数据类型。
比如:Content-Type:text/html;
代表发送端发送的数据格式是html

Content-Type 被指定为 application/x-www-form-urlencoded;例如 JQuery 和 QWrap 的 Ajax,Content-Type 默认值都是「application/x-www-form-urlencoded;charset=utf-8」

作者链接:https://www.jianshu.com/p/b5e8f62bd826

上一篇下一篇

猜你喜欢

热点阅读