标签:
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方法請求
无参数方式:
1
2
3
4
5
6
|
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); }]; |
有参数方式,其实和无参一样:
1
2
3
4
5
6
7
8
9
10
11
|
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请求方式:
1
2
3
4
5
6
7
|
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下):
1
|
self .acceptableContentTypes = [ NSSet setWithObjects:@ "application/json" , @ "text/json" , @ "text/javascript" , nil ]; |
如果返回的数类是text/plain 则会报错。
直接加上该类型即可:
1
|
self .acceptableContentTypes = [ NSSet setWithObjects:@ "text/plain" , @ "application/json" , @ "text/json" , @ "text/javascript" , nil ]; |
标签:
原文地址:http://www.cnblogs.com/xvewuzhijing/p/4904649.html