AFNetworkingiOS开发中常用第三方框架的深度学习AFN

AFNetworking源码解析

2016-01-13  本文已影响4585人  AKyS佐毅

AFNetworking serializer 分析

AFNetworking.png AFNetworkResponse.png

1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
所有的网络请求,均有manager发起
2. 需要注意的是,默认提交请求的数据是二进制的,返回格式是JSON
如果提交数据是JSON的,需要将请求格式设置为AFJSONRequestSerializer

  3. 请求格式
   AFHTTPRequestSerializer            二进制格式
   AFJSONRequestSerializer            JSON
   AFPropertyListRequestSerializer    PList(是一种特殊的XML,解析起来相对容易)
 
  4. 返回格式
   AFHTTPResponseSerializer           二进制格式
   AFJSONResponseSerializer           JSON
   AFXMLParserResponseSerializer      XML,只能返回XMLParser,还需要自己通过代理方法解析
   AFXMLDocumentResponseSerializer (Mac OS X)
   AFPropertyListResponseSerializer   PList
   AFImageResponseSerializer          Image
   AFCompoundResponseSerializer       组合

演示代码如下:

  一:提交数据是JSON格式
   NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
   [dict setObject:@"apple" forKey:@"brand"];
   NSString *url=@"http://xxxxx";
   AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   manager.responseSerializer = [AFJSONResponseSerializer serializer];//申明返回的结果是json类型
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//如果报接受类型不一致请替换一致text/html或别的
   manager.requestSerializer=[AFJSONRequestSerializer serializer];//申明请求的数据是json类型
   [manager POST:url parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {

   } failure:^(AFHTTPRequestOperation *operation, NSError *error){

  }
];
  二:提交数据是NSData类型,即默认类型
       NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
       NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
       NSURLRequest *request = [NSURLRequest requestWithURL:url];
       AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
       [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, idresponseObject) {
        NSString *html = operation.responseString;
        NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
        id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
         NSLog(@"获取到的数据为:%@",dict);
   }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发生错误!%@",error);
}];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
   将所有的网络请求都放入一个线程队列中。

 三:上传图片操作:
     UIImage * image = [UIImage imageNamed:@"imike.png"];
     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@", str];
    NSDictionary *parameters = @{@"filename":fileName};

    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
   //如果报接受类型不一致请替换一致text/html或别的
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager POST:@"http://XXX" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
      // 上传图片,以文件流的格式
     [formData appendPartWithFileData:imageData name:@"img" fileName:fileName mimeType:@"image/png"];
    
   } success:^(AFHTTPRequestOperation *operation, id responseObject){        
        NSLog(@"%@",responseObject);  
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  }];
四:下载图片:
   NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
   AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

   NSURL *URL = [NSURL URLWithString:@"http://192.168.40.10/FileDownload/WebForm1.aspx"];
   NSURLRequest *request = [NSURLRequest requestWithURL:URL];
   NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
   NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
       return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
  } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
       NSLog(@"File downloaded to: %@", filePath);
 }];
   [downloadTask resume];

常见的AFNetworking content-type 报错问题整理(AFNetworking 中请求数据和 HTTP 的 Content-type 关系)

  问题一:  unacceptable content-type: text/plain
      { status code: 200, headers {
        "Content-Length" = 14;
        "Content-Type" = "text/plain;charset=utf-8";
        Date = "Thu, 22 May 2014 10:37:50 GMT";
        Server = "Apache-Coyote/1.1";
       "Set-Cookie" ="JSESSIONID=C0DFED60A154557F8386E62AB2A066CE; Path=/FHJRDT";
} }, NSLocalizedDescription=Request failed:unacceptable content-type: text/plain}

    manager.responseSerializer = [AFHTTPResponseSerializerserializer]; 决定了下面responseObject返回的类型 

主要理解一下几个参数的区别:
          AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
 
    //    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    //    [manager.requestSerializer setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
 
    //注意:默认的Response为json数据
    //    [manager setResponseSerializer:[AFXMLParserResponseSerializer  new]];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//使用这个将得到的是NSData
          manager.responseSerializer = [AFJSONResponseSerializer serializer];//使用这个将得到的是JSON
 
     //注意:此行不加也可以
          manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];

    另外如果AFURLResponseSerialization,告诉AFNetworking 以怎样的方式接受数据,如果后段接口都是标准的JSON数据格式,那么很愉快的就选择了 AFJSONResponseSerializer ,在请求成功的Block中的responseObject 就会是一个 AFNetworking 帮你解好档的JSON,也就是一个 NSDictionary对象。

    但有时候你是否遇到明明接口是返回的JSON数据,可用 AFJSONResponseSerializer 就会报错,错误信息类似:
    Request failed: unacceptable content-type: text/html
content-type返回格式不是JSON格式.png 请求参数不满足JSON格式.png
 如果接口返回的 Content-Type 和实际情况不合时,有时候是因为后端开发人员不规范,更有遇到一套接口中大多都是JSON返回,还有个别方法返回纯文本,如:“YES”,这些都是接口开发人员不规范导致的问题,作为iOS端,解决方案:

 responseSerializer 使用 AFHTTPResponseSerializer,这样就不能享受 AFNetworking 自带的JSON解析功能了,拿到 responseObject 就是一个 Data 对象,需要自己根据需要进行反序列化。
 #pragma mark - Public Method
- (void)postWithManager:(id)requestOperationManager
                     success:(HttpRequestPostSuccessBlock)success
                     failure:(HttpRequestPostFailureBlock)failure{

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];

[manager POST:[NSString stringWithFormat:@"%@%@", self.baseUrl, self.urlString]
   parameters:_parameters
      success:^(AFHTTPRequestOperation * _Nonnull operation,
                id  _Nonnull responseObject) {
          
    if (!operation.isCancelled) {
        NSString *reponStr = operation.responseString;
        NSData* data=[reponStr dataUsingEncoding:NSUTF8StringEncoding];
        id dict=[NSJSONSerialization  JSONObjectWithData:data options:0 error:nil];
        NSLog(@"获取到的数据为:%@",dict);
        //成功
        if (success!=nil) {
            success(dict);
        }
    }
   } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        if (!operation.isCancelled) {
              if (failure!=nil) {
                  failure(operation,error);
              }
       }
  }];
}
上一篇下一篇

猜你喜欢

热点阅读