AFNetworking请求各种类型的数据备忘笔记
AFNetworking是一个轻量级的iOS网络通信类库。它建立在NSURLConnection和NSOperation等类库的基础上,让很多网络通信功能的实现变得十分简单。它支持HTTP请求和基于REST的网络服务(包括GET、POST、 PUT、DELETE等)。支持ARC。Github地址:https://github.com/AFNetworking/AFNetworking
```
1. //
2. // MJViewController.m
3. // 03.AFN演练
4. //
5. // Created by apple on 14-4-30.
6. // Copyright (c) 2014年 itcast. All rights reserved.
7. //
8.
9. #import "MJViewController.h" 10. #import "AFNetworking.h"
11.
12. @interface MJViewController ()
13.
14. @end
15.
16. @implementation MJViewController
17. /**
18. 要使用常规的AFN网络访问
19.
20. 1. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
21.
22. 所有的网络请求,均有manager发起
23.
24. 2. 需要注意的是,默认提交请求的数据是二进制的,返回格式是JSON
25.
26. 1> 如果提交数据是JSON的,需要将请求格式设置为AFJSONRequestSerializer 27. 2> 如果返回格式不是JSON的,
28.
29. 3. 请求格式 30.
31. AFHTTPRequestSerializer 二进制格式
32. AFJSONRequestSerializer JSON
33. AFPropertyListRequestSerializer PList(是一种特殊的XML,解析起来相对容易)
34.
35. 4. 返回格式
36.
37. AFHTTPResponseSerializer 二进制格式
38. AFJSONResponseSerializer JSON
39. AFXMLParserResponseSerializer XML,只能返回XMLParser,还需要自己通过代理方法解析
40. AFXMLDocumentResponseSerializer (Mac OS X)
41. AFPropertyListResponseSerializer Plist
42. AFImageResponseSerializer Image
43. AFCompoundResponseSerializer 组合
44. */ 45. 46. - (void)viewDidLoad
47. { 48. [super viewDidLoad];
49.
50. [self reach]; 51. }
52. 53. #pragma mark - 演练
54. #pragma mark - 检测网络连接
55. - (void)reach 5
6. { 57. /**
58. AFNetworkReachabilityStatusUnknown = -1, // 未知
59. AFNetworkReachabilityStatusNotReachable = 0, // 无连接
60. AFNetworkReachabilityStatusReachableViaWWAN = 1, // 3G 花钱
61. AFNetworkReachabilityStatusReachableViaWiFi = 2, // 局域网络,不花钱 62. */
63. // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring 64. [[AFNetworkReachabilityManager sharedManager] startMonitoring];
65.
66. // 检测网络连接的单例,网络变化时的回调方法
67. [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
68. NSLog(@"%d", status);
69. }];
70. }
71.
72. #pragma mark - Session 下载
73. - (void)sessionDownload
74. {
75. NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
76. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
77.
78. NSString *urlString = @"http://localhost/itcast/videos/01.C语言-语法预览.mp4";
79. urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
80.
81. NSURL *url = [NSURL URLWithString:urlString];
82. NSURLRequest *request = [NSURLRequest requestWithURL:url];
83.
84. NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
85. // 指定下载文件保存的路径
86. // NSLog(@"%@ %@", targetPath, response.suggestedFilename);
87. // 将下载文件保存在缓存路径中
88. NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
89. NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
90.
91. // URLWithString返回的是网络的URL,如果使用本地URL,需要注意
92. NSURL *fileURL1 = [NSURL URLWithString:path];
93. NSURL *fileURL = [NSURL fileURLWithPath:path];
94.
95. NSLog(@"== %@ |||| %@", fileURL1, fileURL);
96.
97. return fileURL;
98. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
99. NSLog(@"%@ %@", filePath, error); 100. }];
101.
102. [task resume];
103. }
104.
105. #pragma mark - POST JSON
106. - (void)postJSON
107. {
108. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
109.
110. NSDictionary *dict = @{@"name": @"zhangsan"};
111. NSDictionary *dict1 = @{@"name": @"wangwu"};
112. NSArray *array = @[dict, dict1];
113. // 设置请求格式
114. manager.requestSerializer = [AFJSONRequestSerializer serializer]; 115. // 设置返回格式
116. manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 117.
118. [manager POST:@"http://localhost/postjson.php" parameters:array success:^(AFHTTPRequestOperation *operation, id responseObject) {
119. NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
120.
121. NSLog(@"%@", result);
122. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
123.
124. }];
125.
126. }
127.
128. #pragma mark - 随机文件名上传
129. - (void)postUpload1
130. {
131. // 本地上传给服务器时,没有确定的URL,不好用MD5的方式处理
132. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
133. manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 134.
135. [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(idformData) {
136.
137. NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];
138.
139. // 要上传保存在服务器中的名称
140. // 使用时间来作为文件名 2014-04-30 14:20:57.png
141. // 让不同的用户信息,保存在不同目录中
142. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
143. // 设置日期格式
144. formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
145. NSString *fileName = [formatter stringFromDate:[NSDate date]]; 146.
147. [formData appendPartWithFileURL:fileURL name:@"uploadFile" fileName:fileName mimeType:@"image/png" error:NULL];
148.
149. } success:^(AFHTTPRequestOperation *operation, id responseObject) { 150. NSLog(@"OK");
151. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
152. NSLog(@"error");
153. }];
154. }
155.
156. #pragma mark - POST上传
157. - (void)postUpload
158. {
159. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
160. // AFHTTPResponseSerializer就是正常的HTTP请求响应结果:NSData
161. // 当请求的返回数据不是JSON,XML,PList,UIImage之外,使用AFHTTPResponseSerializer
162. // 例如返回一个html,text...
163. //
164. // 实际上就是AFN没有对响应数据做任何处理的情况
165. manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 166.
167. // formData是遵守了AFMultipartFormData的对象
168. [manager POST:@"http://localhost/demo/upload.php" parameters:nil constructingBodyWithBlock:^(idformData) {
169.
170. // 将本地的文件上传至服务器
171. NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];
172.
173. [formData appendPartWithFileURL:fileURL name:@"uploadFile" error:NULL];
174. } success:^(AFHTTPRequestOperation *operation, id responseObject) {
175. NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
176.
177. NSLog(@"完成 %@", result);
178. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
179. NSLog(@"错误 %@", error.localizedDescription);
180. }];
181. }
182.
183. #pragma mark - JSON
184. - (void)XMLData
185. {
186. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
187.
188. // 返回的数据格式是XML
189. manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
190.
191. NSDictionary *dict = @{@"format": @"xml"};
192.
193. // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
194. [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
195.
196. // 如果结果是XML,同样需要使用6个代理方法解析,或者使用第三方库
197. // 第三方库第三方框架,效率低,内存泄漏
198. NSLog(@"%@", responseObject);
199. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
200. NSLog(@"%@", error);
201. }];
202. }
203.
204. #pragma mark - JSON
205. - (void)JSONData
206. {
207. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
208.
209. // 原本需要拼接get访问URL ? & =
210. NSDictionary *dict = @{@"format": @"json"};
211.
212. // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
213. [manager GET:@"http://localhost/videos.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
214. NSLog(@"%@", responseObject);
215. // 提问:NSURLConnection异步方法回调,是在子线程
216. // 得到回调之后,通常更新UI,是在主线程
217. NSLog(@"%@", [NSThread currentThread]);
218. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
219. NSLog(@"%@", error);
220. }];
221. }
222.
223. #pragma mark - POST登录
224. - (void)postLogin
225. {
226. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
227.
228. // 原本需要拼接get访问URL ? & =
229. NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};
230.
231. // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
232. [manager POST:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
233. NSLog(@"%@", responseObject);
234. // 提问:NSURLConnection异步方法回调,是在子线程
235. // 得到回调之后,通常更新UI,是在主线程
236. NSLog(@"%@", [NSThread currentThread]);
237. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
238. NSLog(@"%@", error);
239. }];
240. }
241.
242. #pragma mark - GET登录
243. - (void)getLogin
244. {
245. AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
246.
247. // 原本需要拼接get访问URL ? & =
248. NSDictionary *dict = @{@"username": @"wangwu", @"password" : @"wang"};
249.
250. // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
251. [manager GET:@"http://localhost/login.php" parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
252. NSLog(@"%@", responseObject);
253. // 提问:NSURLConnection异步方法回调,是在子线程
254. // 得到回调之后,通常更新UI,是在主线程
255. NSLog(@"%@", [NSThread currentThread]);
256. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
257. NSLog(@"%@", error);
258. }];
259. }
260.```
@end
网友评论