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

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

原生方式同步GET请求:

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

原生方式异步GET请求:

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

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

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

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

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

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

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

 #import "AFNetworking.h"

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

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

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

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

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

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

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

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

     //目标地址
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/img/baidu_sylogo1.gif"];
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //构建AFN操作
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request]; //设置输出流
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *downloadPath = [documents[] stringByAppendingPathComponent:@"1.gif"];
[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:NO]]; //下载过程当中的block(检测进度)
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(@"下载百分比:%f", (float)totalBytesRead / totalBytesExpectedToRead);
}]; //下载完成
[operation setCompletionBlock:^{
NSLog(@"操作完成");
}];
上一篇:PHP递归生成树形数组


下一篇:avalon1.0正式发布