原生网络请求以及AFN网络请求/异步下载

这里对网络请求方式做一个总结。

原生方式同步GET请求:

1     NSString *urlStr = @"http://apis.juhe.cn/mobile/get?phone=13429667914&key=e87a054855796995c9e2b48e8514d0da";
2     urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
3     NSURL *url = [NSURL URLWithString:urlStr];
4     NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
5     NSURLResponse *response = nil;
6     NSError *error = nil;
7     NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
8     NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
9     NSLog(@"%@", responseString);

原生方式异步GET请求:

1     NSString *urlStr = @"http://apis.juhe.cn/mobile/get?phone=13429667914&key=e87a054855796995c9e2b48e8514d0da";
2     urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
3     NSURL *url = [NSURL URLWithString:urlStr];
4     NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
5     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
6         NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
7         NSLog(@"%@", responseString);
8     }];

可见,请求分为两部分,一是构建请求,二是发送请求。构建分为GET和POST,发送分为同步和异步。

POST请求的请求部分需要将参数构建为NSData类型:

 1     NSString *urlStr = @"http://apis.juhe.cn/mobile/get?";
 2     urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
 3     NSURL *url = [NSURL URLWithString:urlStr];
 4     
 5     //创建请求,配置参数的data
 6     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
 7     [request setHTTPMethod:@"POST"];
 8     NSString *otherURLstr = @"phone=13429667914&key=e87a054855796995c9e2b48e8514d0da";
 9     NSData *otherURLData = [otherURLstr dataUsingEncoding:NSUTF8StringEncoding];
10     [request setHTTPBody:otherURLData];

 

原生方式写出来的代码总是一坨,下面看看AFN对请求的封装。AFN需要添加MobileCoreService和SystemConfiguration框架,并在pch里加入头文件:

1     #import <MobileCoreServices/MobileCoreServices.h>
2     #import <SystemConfiguration/SystemConfiguration.h>

在使用时需要引入头文件:

1 #import "AFNetworking.h"

GET和POST的请求的构建还是和前面一样,发送处:

1     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
2     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
3         NSLog(@"%@", operation.responseString);
4     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
5         NSLog(@"%@", [error localizedDescription]);
6     }];
7     [operation start];

AFHTTPRequestOperation是操作队列的子类,显然AFN的请求是异步的(当然,既然是操作队列,就可以用操作队列的方法控制它),请求完成后触发回调。

AFN支持自动解析JSON并转化为词典结构:

1     AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
2         NSLog(@"%@", JSON);
3     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
4     }];
5     [operation start];

但是个人不建议使用它解析XML,因为它采用的是XMLParser的方式,很繁琐。

 

但是这还是显得一坨一坨的,于是有两种办法,第一种就是再封装一层简单的API,就像jQueryAjax一样,第二种就是每次用的时候复制粘贴啦~

 

使用AFN也可以很方便地实现文件异步下载:

 1     //目标地址
 2     NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/img/baidu_sylogo1.gif"];
 3     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 4 
 5     //构建AFN操作
 6     AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
 7     
 8     //设置输出流
 9     NSArray *documents = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
10     NSString *downloadPath = [documents[0] stringByAppendingPathComponent:@"1.gif"];
11     [operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:NO]];
12     
13     //下载过程当中的block(检测进度)
14     [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
15         NSLog(@"下载百分比:%f", (float)totalBytesRead / totalBytesExpectedToRead);
16     }];
17     
18     //下载完成
19     [operation setCompletionBlock:^{
20         NSLog(@"操作完成");
21     }];

 

posted @ 2014-07-04 10:56  肉排君  阅读(646)  评论(0编辑  收藏  举报