AFNetworking 2.0 使用总结

jopen 6年前

iOS应用开发,存在网络请求是在所难免的,而AFNetworking是一个很不错的选择。以下是本人对AFNetworking请求的一些总结,但愿能帮到大家!

1.JSON Post请求

        NSString *strName = @"user1";          NSString *strPsw = @"pwd1";                    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];          manager.requestSerializer = [AFJSONRequestSerializer serializer];          NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:strName, @"user", strPsw, @"password", nil];          NSString *strURL = [GT123_ServerHost stringByAppendingString:GT123_LogonServlet];          [manager POST:strURL parameters:parameters                success:^(AFHTTPRequestOperation *operation, id responseObject)           {               if (responseObject != nil)               {                   NSDictionary *dicRes = responseObject;                   NSString *strState = [dicRes objectForKey:@"state"];                   if (strState && [strState isEqualToString:@"success"])                   {                       NSString *strSession = [dicRes objectForKey:@"session"];                                              NSLog(@"%@", strSession);                   } else {                   }               } else {               }           } failure:^(AFHTTPRequestOperation *operation, NSError *error)           {           }];
上段代码是用户登录请求,用到了AFHTTPRequestOperationManager的POST请求。请求参数放到NSDictionary里(NSMutableDictionary也可),strURL是请求服务地址,success和failure后面写请求回调内容。返回内容responseObject其实是一个NSDictionary对象,解析比较容易。

2.JSON Get请求

        long long lTimestamp = [[NSDate date] timeIntervalSince1970] * 1000;                    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];          NSString *strURL = [NSString stringWithFormat:@"%@%@?max=20&et=%lld",GT123_ServerHost,GT123_GetNewsListBeforeServlet, lTimestamp];          [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {              if (responseObject != nil)              {                  NSDictionary *dicRes = responseObject;                  NSString *strState = [dicRes objectForKey:@"state"];                  if (strState && [strState isEqualToString:@"success"])                  {                      NSArray *lNews = [dicRes objectForKey:@"post_list"];                      if (lNews && lNews.count > 0)                      {                          NSLog(@"news count - %lu", (unsigned long)lNews.count);                      }                  } else {                  }              } else              {              }          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {          }];
上段代码是获取新闻列表的具体实现,用到了AFHTTPRequestOperationManager的GET请求。所以请求参数放到strURL里。请求返回内容responseObject也是一个NSDictionary对象。

</div>

3.图片上传

- (void)uploadImg:(UIImage *)img withName:(NSString *)imgName {            NSData *imageData = UIImageJPEGRepresentation(img, 1.0);            NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];      [parameters setObject:imgName forKey:@"name"];      [parameters setObject:@"jpg" forKey:@"type"];            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];      manager.requestSerializer = [AFJSONRequestSerializer serializer];      NSString *strURL = [GT123_ServerHost stringByAppendingString:GT123_UploadPostPictureServlet];      [manager POST:strURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)       {           if (imageData)           {               [formData appendPartWithFileData:imageData name:imgName fileName:imgName mimeType:@"image/jpeg"];           }       } success:^(AFHTTPRequestOperation *operation, id responseObject) {                      if (responseObject)           {               NSDictionary *dicRes = responseObject;               NSString *strState = [dicRes objectForKey:@"state"];               if (strState && [strState isEqualToString:@"success"])               {                   NSLog(@"upload success!");               } else {               }           } else {           }                  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {       }];  }
以上代码通过post方法将图片上传到服务器。与上述所讲json post请求不同,这里需要填充constructingBodyWithBlock内容,也就是图片数据和参数。图片数据是NSData类型,需要将UIImage转成NSData。如果需要传其他参数的话,放到parameters里,同图片数据一起上传服务器。

[formData appendPartWithFileData:imageData name:imgName fileName:imgName mimeType:@"image/jpeg"];
上一行代码里name和fileName参数可以随意给个值,不要太纠结。

返回内容还是一个NSDictionary对象。


AFNetworking请求方面,本人的总结暂时有这些,后续再补上...