iOS中AFNetworking的简单使用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS中AFNetworking的简单使用相关的知识,希望对你有一定的参考价值。
GET:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// 1.获得请求管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.封装请求参数 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@ "userId" ] = [appDefault objectForKey:@ "userId" ]; params[@ "IMSI" ] = _IMSI.text; params[@ "nickName" ] = _nickName.text; params[@ "phoneNumber" ] = _phoneNumber.text; NSString *url = [ServiceInfo stringByAppendingString:@ "http://103.238.80.57:8080/Vietnam/Application/bindingDevice" ]; // 3.发送GET请求 [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@ "%@" ,responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@ "%@" ,error); }]; |
POST:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// 1.获得请求管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 2.封装请求参数 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@ "userId" ] = [appDefault objectForKey:@ "userId" ]; params[@ "IMSI" ] = _IMSI.text; params[@ "nickName" ] = _nickName.text; params[@ "phoneNumber" ] = _phoneNumber.text; NSString *url = [ServiceInfo stringByAppendingString:@ "http://103.238.80.57:8080/Vietnam/Application/bindingDevice" ]; // 3.发送GET请求 [mgr POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@ "%@" ,responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@ "%@" ,error); }]; |
值得注意的是,AFNetworking默认是使用JSON格式发送和响应返回来的数据的,如果返回来的数据不是JSON,就需要设置一下请求管理者,下面请看代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
// 1.获得请求管理者 AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // 因为传递过去和接收回来的数据都不是json类型的,所以在这里要设置为AFHTTPRequestSerializer和AFHTTPResponseSerializer mgr.requestSerializer = [AFHTTPRequestSerializer serializer]; // 请求 mgr.responseSerializer = [AFHTTPResponseSerializer serializer]; // 响应 // 2.封装请求参数 NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@ "userId" ] = [appDefault objectForKey:@ "userId" ]; params[@ "IMSI" ] = _IMSI.text; params[@ "nickName" ] = _nickName.text; params[@ "phoneNumber" ] = _phoneNumber.text; NSString *url = [ServiceInfo stringByAppendingString:@ "http://103.238.80.57:8080/Vietnam/Application/bindingDevice" ]; // 3.发送GET请求 [mgr GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 转码,如果返回的数据不是JSON,这里必须要转码 NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]; NSLog(@ "%@" ,string); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@ "%@" ,error); }]; |
以上是关于iOS中AFNetworking的简单使用的主要内容,如果未能解决你的问题,请参考以下文章
ios开发之--使用AFNetWorking 3.1.0 ,简单的请求封装类
无法在 ios 中使用 afnetworking 发布 JSON