AFNetworking学习与使用(一)


HTTP请求操作管理

     AFHttpRequestOperationManager封装了通过HTTP与Web应用程序通信的一般模式,包括:请求创建、响应序列化、网络可达性监控和安全性,当然也包括HTTP请求操作管理。

GET请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager  manager];
[manager  GET: @"http://example.com/resources.json"  parameters: nil  success:^(AFHTTPRequestOperation *operation,  id responseObject) {
    NSLog( @"JSON: %@", responseObject);
failure:^(AFHTTPRequestOperation *operation,  NSError *error) {
    NSLog( @"Error: %@", error);
}];

POST网址形式编码的请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager  manager];
NSDictionary *parameters = @{ @"foo"@"bar"};
[manager  POST: @"http://example.com/resources.json"  parameters:parameters  success:^(AFHTTPRequestOperation *operation,  id responseObject) {
    NSLog( @"JSON: %@", responseObject);
failure:^(AFHTTPRequestOperation *operation,  NSError *error) {
    NSLog( @"Error: %@", error);
}];

POST多表请求

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager  manager];
NSDictionary *parameters = @{ @"foo"@"bar"};
NSURL *filePath = [ NSURL  fileURLWithPath: @"file://path/to/image.png"];
[manager  POST: @"http://example.com/resources.json"  parameters:parameters  constructingBodyWithBlock:^( id<AFMultipartFormData> formData) {
    [formData  appendPartWithFileURL:filePath  name: @"image"  error: nil];
success:^(AFHTTPRequestOperation *operation,  id responseObject) {
    NSLog( @"Success: %@", responseObject);
failure:^(AFHTTPRequestOperation *operation,  NSError *error) {
    NSLog( @"Error: %@", error);
}];




AFURLSessionManager

AFURLSessionManager 在一个规定的NSURLSessionConfiguration对象的基础上创建和管理一个NSURLSession对象,,并且遵从代理: <NSURLSessionTaskDelegate> , <NSURLSessionDataDelegate> <NSURLSessionDownloadDelegate> , 和  <NSURLSessionDelegate>

创建一个上传任务

NSURLSessionConfiguration *configuration = [ NSURLSessionConfiguration  defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager  allocinitWithSessionConfiguration:configuration];

NSURL *URL = [ NSURL  URLWithString: @"http://example.com/upload"];
NSURLRequest *request = [ NSURLRequest  requestWithURL:URL];

NSURL *filePath = [ NSURL  fileURLWithPath: @"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager  uploadTaskWithRequest:request  fromFile:filePath  progress: nil  completionHandler:^( NSURLResponse *response,  id responseObject,  NSError *error) {
    if (error) {
        NSLog( @"Error: %@", error);
    }  else {
        NSLog( @"Success: %@ %@", response, responseObject);
    }
}];
[uploadTask  resume];

创建一个带多表和进度的上传任务

NSMutableURLRequest *request = [[AFHTTPRequestSerializer  serializermultipartFormRequestWithMethod: @"POST"  URLString: @"http://example.com/upload"  parameters: nil  constructingBodyWithBlock:^( id<AFMultipartFormData> formData) {
        [formData  appendPartWithFileURL:[ NSURL  fileURLWithPath: @"file://path/to/image.jpg"name: @"file"  fileName: @"filename.jpg"  mimeType: @"image/jpeg"  error: nil];
    }  error: nil];

AFURLSessionManager *manager = [[AFURLSessionManager  allocinitWithSessionConfiguration:[ NSURLSessionConfiguration  defaultSessionConfiguration]];
NSProgress *progress =  nil;

NSURLSessionUploadTask *uploadTask = [manager  uploadTaskWithStreamedRequest:request  progress:&progress  completionHandler:^( NSURLResponse *response,  id responseObject,  NSError *error) {
    if (error) {
        NSLog( @"Error: %@", error);
    }  else {
        NSLog( @"%@ %@", response, responseObject);
    }
}];

[uploadTask  resume];

创建一个数据流Data任务

NSURLSessionConfiguration *configuration = [ NSURLSessionConfiguration  defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager  allocinitWithSessionConfiguration:configuration];

NSURL *URL = [ NSURL  URLWithString: @"http://example.com/upload"];
NSURLRequest *request = [ NSURLRequest  requestWithURL:URL];

NSURLSessionDataTask *dataTask = [manager  dataTaskWithRequest:request  completionHandler:^( NSURLResponse *response,  id responseObject,  NSError *error) {
    if (error) {
        NSLog( @"Error: %@", error);
    }  else {
        NSLog( @"%@ %@", response, responseObject);
    }
}];
[dataTask  resume];




请求序列化

请求序列化是指创建以URL字符串、编码参数作为查询字符串或HTTP主题的请求。
NSString *URLString =  @"http://example.com";
NSDictionary *parameters = @{ @"foo"@"bar"@"baz": @[@ 1, @ 2, @ 3]};

查询字符串参数编码

[[AFHTTPRequestSerializer  serializer  ]  requestWithMethod:  @" GET "   URLString:  URLString  parameters:  parameters  error:  nil  ];

URL格式参数编码

[[AFHTTPRequestSerializer  serializerrequestWithMethod: @"POST"  URLString:URLString  parameters:parameters];

JSON参数编码

[[AFJSONRequestSerializer  serializerrequestWithMethod: @"POST"  URLString:URLString  parameters:parameters];




网络可达性管理

AFNetworkingReachabilityManager监控WWAN和WIFI网络的接口地址的可达性。
注意:
  • 不要使用Reachability来确定原始请求是否应该发送(你应该尝试发送)
  • 你可以使用Reachability来确定什么时候一个请求应该被自动重新尝试。(尽管请求仍旧可能失败,但是当一个Reachability发送连通性可用,是重新尝试一些请求的最佳时机。)
  • 网络可达性是一个有用的工具,它可以确定为什么一个请求可能会失败。(当请求失败时,它告诉用户一些精确的错误)

共享Network Reachability

[[AFNetworkReachabilityManager  sharedManagersetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog( @"Reachability: %@"AFStringFromNetworkReachabilityStatus(status));
}];

[[AFNetworkReachabilityManager  sharedManagerstartMonitoring];

HTTP Manager Reachability

NSURL *baseURL = [ NSURL  URLWithString: @"http://example.com/"];
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager  allocinitWithBaseURL:baseURL];

NSOperationQueue *operationQueue = manager.operationQueue;
[manager.reachabilityManager  setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            [operationQueue  setSuspended: NO];
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            [operationQueue  setSuspended: YES];
            break;
    }
}];

[manager.reachabilityManager  startMonitoring];




安全策略

AFSecurityPolicy评估服务器对X.509证书和通过安全连接的公共秘钥是否信任。
增加固定的SSL证书到你的应用程序有助于防止人为攻击和其他安全漏洞。 应用程序处理敏感的客户数据或财务信息,我们强烈建议HTTPS连接配置和启用SSL。

允许无效的SSL证书

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager  manager];
manager.securityPolicy.allowInvalidCertificates =  YES// not recommended for production




AFHttpRequestOperation

AFHTTPRequestOperation是使用HTTP或HTTPS协议的AFURLConnectionOperation的子类。 封装获取的HTTP状态和类型来表示请求的成功与否。
虽然AFHTTPRequestOperationManager通常是提出请求的最佳方式,但是AFHTTPRequestOperation可以单独使用。

GET与AFHTTPRequestOperation

NSURL *URL = [ NSURL  URLWithString: @"http://example.com/resources/123.json"];
NSURLRequest *request = [ NSURLRequest  requestWithURL:URL];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation  allocinitWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer  serializer];
[op  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,  id responseObject) {
    NSLog( @"JSON: %@", responseObject);
failure:^(AFHTTPRequestOperation *operation,  NSError *error) {
    NSLog( @"Error: %@", error);
}];
[[ NSOperationQueue  mainQueueaddOperation:op];


批量多请求

NSMutableArray *mutableOperations = [ NSMutableArray  array];
for ( NSURL *fileURL in filesToUpload) {
    NSURLRequest *request = [[AFHTTPRequestSerializer  serializermultipartFormRequestWithMethod: @"POST"  URLString: @"http://example.com/upload"  parameters: nil  constructingBodyWithBlock:^( id<AFMultipartFormData> formData) {
        [formData  appendPartWithFileURL:fileURL  name: @"images[]"  error: nil];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation  allocinitWithRequest:request];

    [mutableOperations  addObject:operation];
}

NSArray *operations = [AFURLConnectionOperation  batchOfRequestOperations:@[...]  progressBlock:^( NSUInteger numberOfFinishedOperations,  NSUInteger totalNumberOfOperations) {
    NSLog( @"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
completionBlock:^( NSArray *operations) {
    NSLog( @"All operations in batch complete");
}];
[[ NSOperationQueue  mainQueueaddOperations:operations  waitUntilFinished: NO];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值