AFNetworking2.x学习

来源:互联网 发布:枪托在淘宝怎么找 编辑:程序博客网 时间:2024/05/23 01:56

一.用法(翻译于Github-AFNetworking-https://github.com/AFNetworking/AFNetworking)

1.HTTP Request Operation Manager

   AFHttpRequestOperationManager封装了基于HTTP的web应用交互的常用模式,包含了请求的创建,响应的序列化,网络可达性管理和安全等请求操作管理

1)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);}];

2)POST URL格式编码请求

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);}];


3)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(@"json : %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {  NSLog(@"Error :%@", error);}];

2.AFURLSessionManager

  AFURLSessionManager创建和管理着基于指定的NSURLSessionConfiguration的NSURLSession对象,该对象遵循了NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSURLSessionDelegate.

1)创建下载任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];NSURLSessionManager *manager = [[AFURLSessionManager alloc] initWIthSessionConfiguration:configuration];NSURL *url = [NSURL URLWithString:@"http://example.com/download.zip"];NSURLRequest *request = [NSURLRequest requestWithURL:url];NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *reponse) {  NSURL *docunmentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocument 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];

2)创建上传任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];NSURLSessionManager *manager = [[AFURLSessionManager alloc] initWIthSessionConfiguration:configuration];NSURL *url = [NSURL URLWithString:@"http://example.com/upload];NSURLRequest *request = [NSURLRequest requestWithURL:url];NSURL *filePath = [NSURL fileURLWithPath:@"file://paht/to/image.png"];NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *reponse, id responseObject, NSError *error) { if (error) {    NSLog(@"Error: %@", error); } else {    NSLog(@"Success: %@ %@", response, responseObject); }}];[uploadTask resume];

3)创建多部分请求以及包含进度的上传任务

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"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 alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defultSessionConfiguration]];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];

4)创建数据任务

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];NSURLSessionManager *manager = [[AFURLSessionManager alloc] initWIthSessionConfiguration:configuration];NSURL *url = [NSURL URLWithString:@"http://example.com/upload];NSURLRequest *request = [NSURLRequest requestWithURL:url];NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *reponse, id responseObject, NSError *error) { if (error) {    NSLog(@"Error: %@", error); } else {    NSLog(@"Success: %@ %@", response, responseObject); }}];[dataTask resume];

3.请求序列化

请求序列化将URL字符串和编码参数变成如同序列化字符和HTTP body的请求

NSString *URLString = @"http://example.com";NSDictionary *parameters = @{@"foo" : @"bar", @"baz": @[@1, @2, @3]};

1)查询字符串参数编码

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil];
GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3


2)URL格式参数编码

<pre name="code" class="objc"><pre name="code" class="objc">[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

POST http://example.com/

Content-Type: application/x-www-form-urlencoded

foo=bar&baz[]=1&baz[]=2&baz[]=3


3)JSON参数

<span style="color:#000000;">[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];</span>
POST http://example.com/

Content-Type: application/json

{“foo": "bar", "baz": [1, 2, 3]}


4. 网络可达性管理

AFNetworkReachabilityManager监测域的可达性,以及WWAN和WiFi网络接口的地址

1)共享网络的可达性

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

2)HTTP管理可达性

NSURL *baseURL = [NSURL URLWithString:@"http://example.com"];AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL: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];    }}];[manager.reachabilityManager startMonitoring];

5.安全策略

  AFSecurityPolicy封装了固定的X.509服务器信任和安全连接的公用Key

  给app增加固定的SSL证书可以防止中间人攻击和其他危险。

1)允许无效的SSL证书

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];manager.securityPolicy.allowInvalidCertificates = YES;

6.AFHTTPRequestOperation

  AFHTTPRequestOperation是AFURLConnectionOperation的子类,用于HTTP或者HTTPS协议的命令。封装了各种决定请求成功或失败的状态代码和内容类型。


1)AFHTTPRequestOperation的GET

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

2)批量操作

<span style="color:#000000;">NSMutableArray *mutableOperations = [NSMutableArray array];for (NSURL *fileURL in filesToUpload) {  NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMetohd:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  [formData appendPartWithFileURL:fileURL name:@"images[]" error:nil];}];AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest: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 mainQueue] addOperations:operations waitUntilFinished:NO];</span>


0 0
原创粉丝点击