概述
AFNetworking是一個非常受歡迎的輕量級的iOS、Mac OS X網絡通信類庫。它建立在NSURLConnection、NSOperation以及其技術的基礎上,有着精心設計的模塊結構和功能豐富的API,讓很多網絡通信功能的實現變得十分簡單。
AFNetworking支持HTTP請求和基於REST的網絡服務(包括GET、POST、 PUT以及DELETE等)。支持ARC。AFNetworking項目中還包含一些列單元測試。
要求iOS 5.0及以上版本,或者Mac OS 10.7及以上版本。
源碼地址:https://github.com/AFNetworking/AFNetworking
實踐使用
在源碼里,已經介紹得很清楚,下面,為大家貼出部分常用的。
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); }];
有參數方式,其實和無參一樣:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@"param1"] = @"1"; params[@"param2"] = @"2"; [manager GET:@"http://example.com/resources.json" parameters:params 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); }];
另外注意:
我們在請求網絡的時候,經常會看到返回數據時,有頭部信息,如:
Content-Type: application/json
AFNetworking 默認接受的數據類型是(在AFJSONResponseSerializer下):
self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
如果返回的數類是text/plain 則會報錯。
直接加上該類型即可:
self.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"application/json", @"text/json", @"text/javascript", nil];