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

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

原生方式同步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请求:app

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里加入头文件:url

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

在使用时须要引入头文件:spa

1 #import "AFNetworking.h"

GET和POST的请求的构建仍是和前面同样,发送处:code

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的请求是异步的(固然,既然是操做队列,就能够用操做队列的方法控制它),请求完成后触发回调。blog

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     }];
相关文章
相关标签/搜索