AFNetworking框架使用浅析
2015-11-12 09:36
190 查看
目录:
1、为什么要用AFNetworking
2、AFNetworking的用法
一、为什么要用AFNetworking
在ios开发中,一般情况下,简单的向某个web站点简单的页面提交请求并获取服务器的响应,用xcode自带的NSURLConnection是能胜任的。但是,在绝大部分下我们所需要访问的web页面则是属于那种受到权限保护的页面,并不是有一个简单的URL可以访问的。这就涉及到了Session和Cookie的处理了,在此时使用NSURLConnection也是能够达到要求的,只是其中处理起来的复杂度和难度就提升了。
为了更好的处理向Web站点的请求,包括处理Session,Cookie等细节问题,使用AFNetworking则是更好的选择,他可以用于发送HTTP请求,接收HTTP的响应,但是不会缓存服务器的响应,不能执行HTML页面中的JAvascript代码,同时,AFNetworking还内置支持JSON,plist文件和XML文件的解析,使用比较方便。
扩展:1、Session:中文有译作时域的,就是只某个客户端在访问服务器起到停止访问这一段的时间间隔被称为时域。
2、Cookie:由服务器发送给客服端,把Cookie的key:value值储存在本地文件夹下,当下次请求的时候能够直接发送Cookie获得权限验证
二、AFNetworking的用法
1、提交GET请求和提交POST请求
AFNetworking是第三方的框架,所以需要开发者自行下载,安装。并在AFNetworking.h文件导入#import“AFHTTPRequestOpeartionManager.h
”,把AFNetworking.h头文件放入prefix文件中。
a、创建AFHTTPRequestOpeartionManger对象
b、根据服务器内容的不同,为AFHTTPRequestOpeartionManger对象指定不同的解析器,该对象默认的解析器是JSON和Plist文件解析器。如果服务器的数据是XML格式则需要手动的更改解析器
c、发送GET请求:用Manager对象调用GET:parameters:success:failure:方法即可,success代码块和failue代码块在网络请求成功/失败过后调用。
d、success:参数指定了代码块中处理服务器响应成功的正确数据,failue:参数指定了代码块中处理服务器响应失败的错误数据、
AFHTTPRquestOperationManager
包含了常见的HTTP访问web站点的模式,有创建请求,连续的响应,网络类型监视以及安全。
“GET”:
[objc]view
plaincopy
1.<spanstyle="font-size:12px;">//创建AFHTTPRequestOperationManager对象
2.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationMangermanager];
3.//调用get方法
4.[managerGET:@“http://example.com/resources.json”parameters:parameters
5.//加载成功的代码块,可以接收数据
6.success:^(AFHTTPRequestOperation*operation,idresponseobject)]{
7.NSLog(@“json“:%@”,responseObject);
8.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
9.NSLog(@“Error:%@”,error);
10.}];</span>
”POST“:URL-Form-EncodedRequestURL编码请求类型
[objc]view
plaincopy
1.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManagermanager];
2.NSDictionary*parameters=@{@"foo":@"bar"};
3.[managerPOST:@"http://example.com/resources.json"parameters:parameterssuccess:^(AFHTTPRequestOperation*operation,idresponseObject){
4.NSLog(@"JSON:%@",responseObject);
5.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
6.NSLog(@"Error:%@",error);
7.}];
"POST"多个请求
[objc]viewplaincopy
1.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManagermanager];
2.NSDictionary*parameters=@{@"foo":@"bar"};
3.NSURL*filePath=[NSURLfileURLWithPath:@"file://path/to/image.png"];
4.[managerPOST:@"http://example.com/resources.json"parameters:parametersconstructingBodyWithBlock:^(id<AFMultipartFormData>formData){
5.[formDataappendPartWithFileURL:filePathname:@"image"error:nil];
6.}success:^(AFHTTPRequestOperation*operation,idresponseObject){
7.NSLog(@"Success:%@",responseObject);
8.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
9.NSLog(@"Error:%@",error);
10.}];
2、创建一个下载文件的任务
plaincopy
1.NSURLSessionConfiguration*configuration=[NSURLSessionConfigurationdefaultSessionConfiguration];
2.AFURLSessionManager*manager=[[AFURLSessionManageralloc]initWithSessionConfiguration:configuration];
3.
4.NSURL*URL=[NSURLURLWithString:@"http://example.com/download.zip"];
5.NSURLRequest*request=[NSURLRequestrequestWithURL:URL];
6.
7.NSURLSessionDownloadTask*downloadTask=[managerdownloadTaskWithRequest:requestprogress:nildestination:^NSURL*(NSURL*targetPath,NSURLResponse*response){
8.NSURL*documentsDirectoryURL=[[NSFileManagerdefaultManager]URLForDirectory:NSDocumentDirectoryinDomain:NSUserDomainMaskappropriateForURL:nilcreate:NOerror:nil];
9.return[documentsDirectoryURLURLByAppendingPathComponent:[responsesuggestedFilename]];
10.}completionHandler:^(NSURLResponse*response,NSURL*filePath,NSError*error){
11.NSLog(@"Filedownloadedto:%@",filePath);
12.}];
13.[downloadTaskresume];
3、创建一个上传文件的任务
[objc]view
plaincopy
1.NSURLSessionConfiguration*configuration=[NSURLSessionConfigurationdefaultSessionConfiguration];
2.AFURLSessionManager*manager=[[AFURLSessionManageralloc]initWithSessionConfiguration:configuration];
3.
4.NSURL*URL=[NSURLURLWithString:@"http://example.com/upload"];
5.NSURLRequest*request=[NSURLRequestrequestWithURL:URL];
6.
7.NSURL*filePath=[NSURLfileURLWithPath:@"file://path/to/image.png"];
8.NSURLSessionUploadTask*uploadTask=[manageruploadTaskWithRequest:requestfromFile:filePathprogress:nilcompletionHandler:^(NSURLResponse*response,idresponseObject,NSError*error){
9.if(error){
10.NSLog(@"Error:%@",error);
11.}else{
12.NSLog(@"Success:%@%@",response,responseObject);
13.}
14.}];
15.[uploadTaskresume];
4、处理JSON或Plist响应
IOS应用在处理JSON和Plist响应的时候可以十分轻便将其转换成NSDictionary对象或者NSArray对像,AFHTTPRequestOpeartionManager默认就可以处理JSON或Plist响应,也就是说当我们response.MIMEType为appication/json、text/json,AFHTTPRequestOpeartionManager默认就可以处理,无需再次指定服务器响应解析器。
[objc]view
plaincopy
1.
2.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManagermanager];
3.//manager.responseSerializer=[AFHTTPResponseSerializerserializer];
4.NSDictionary*parameter=@{@"location":@"长沙",@"output":@"json",@"ak":@"jlflVx1VTUahj05Q7GfB7PCf"};
5.[managerGET:@"http://api.map.baidu.com/telematics/v3/weather?"parameters:parametersuccess:^(AFHTTPRequestOperation*operation,idresponseObject){
6.NSLog(@"OK");
7.dic=responseObject;
8.NSArray*keys=[dicallKeys];
9.NSLog(@"%@",keys);
10.//_datas=responseObject;
11.//NSString*stringData=[[NSStringalloc]initWithData:_datasencoding:NSUTF8StringEncoding];
12.//NSLog(@"%@",stringData);
13.
14.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
15.NSLog(@"NOTOK");
16.}];
1、为什么要用AFNetworking
2、AFNetworking的用法
一、为什么要用AFNetworking
在ios开发中,一般情况下,简单的向某个web站点简单的页面提交请求并获取服务器的响应,用xcode自带的NSURLConnection是能胜任的。但是,在绝大部分下我们所需要访问的web页面则是属于那种受到权限保护的页面,并不是有一个简单的URL可以访问的。这就涉及到了Session和Cookie的处理了,在此时使用NSURLConnection也是能够达到要求的,只是其中处理起来的复杂度和难度就提升了。
为了更好的处理向Web站点的请求,包括处理Session,Cookie等细节问题,使用AFNetworking则是更好的选择,他可以用于发送HTTP请求,接收HTTP的响应,但是不会缓存服务器的响应,不能执行HTML页面中的JAvascript代码,同时,AFNetworking还内置支持JSON,plist文件和XML文件的解析,使用比较方便。
扩展:1、Session:中文有译作时域的,就是只某个客户端在访问服务器起到停止访问这一段的时间间隔被称为时域。
2、Cookie:由服务器发送给客服端,把Cookie的key:value值储存在本地文件夹下,当下次请求的时候能够直接发送Cookie获得权限验证
二、AFNetworking的用法
1、提交GET请求和提交POST请求
AFNetworking是第三方的框架,所以需要开发者自行下载,安装。并在AFNetworking.h文件导入#import“AFHTTPRequestOpeartionManager.h
”,把AFNetworking.h头文件放入prefix文件中。
a、创建AFHTTPRequestOpeartionManger对象
b、根据服务器内容的不同,为AFHTTPRequestOpeartionManger对象指定不同的解析器,该对象默认的解析器是JSON和Plist文件解析器。如果服务器的数据是XML格式则需要手动的更改解析器
c、发送GET请求:用Manager对象调用GET:parameters:success:failure:方法即可,success代码块和failue代码块在网络请求成功/失败过后调用。
d、success:参数指定了代码块中处理服务器响应成功的正确数据,failue:参数指定了代码块中处理服务器响应失败的错误数据、
AFHTTPRquestOperationManager
包含了常见的HTTP访问web站点的模式,有创建请求,连续的响应,网络类型监视以及安全。
“GET”:
[objc]view
plain
1.<spanstyle="font-size:12px;">//创建AFHTTPRequestOperationManager对象
2.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationMangermanager];
3.//调用get方法
4.[managerGET:@“http://example.com/resources.json”parameters:parameters
5.//加载成功的代码块,可以接收数据
6.success:^(AFHTTPRequestOperation*operation,idresponseobject)]{
7.NSLog(@“json“:%@”,responseObject);
8.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
9.NSLog(@“Error:%@”,error);
10.}];</span>
”POST“:URL-Form-EncodedRequestURL编码请求类型
[objc]view
plain
1.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManagermanager];
2.NSDictionary*parameters=@{@"foo":@"bar"};
3.[managerPOST:@"http://example.com/resources.json"parameters:parameterssuccess:^(AFHTTPRequestOperation*operation,idresponseObject){
4.NSLog(@"JSON:%@",responseObject);
5.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
6.NSLog(@"Error:%@",error);
7.}];
"POST"多个请求
[objc]
1.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManagermanager];
2.NSDictionary*parameters=@{@"foo":@"bar"};
3.NSURL*filePath=[NSURLfileURLWithPath:@"file://path/to/image.png"];
4.[managerPOST:@"http://example.com/resources.json"parameters:parametersconstructingBodyWithBlock:^(id<AFMultipartFormData>formData){
5.[formDataappendPartWithFileURL:filePathname:@"image"error:nil];
6.}success:^(AFHTTPRequestOperation*operation,idresponseObject){
7.NSLog(@"Success:%@",responseObject);
8.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
9.NSLog(@"Error:%@",error);
10.}];
2、创建一个下载文件的任务
AFURLSessionManager创建并完善了一个NSURLSession的对象基于遵从NSURLSessionDelegate与NSURLSessionDataDelegate协议NSURLSessionConfigration对象。
[objc]viewplain
1.NSURLSessionConfiguration*configuration=[NSURLSessionConfigurationdefaultSessionConfiguration];
2.AFURLSessionManager*manager=[[AFURLSessionManageralloc]initWithSessionConfiguration:configuration];
3.
4.NSURL*URL=[NSURLURLWithString:@"http://example.com/download.zip"];
5.NSURLRequest*request=[NSURLRequestrequestWithURL:URL];
6.
7.NSURLSessionDownloadTask*downloadTask=[managerdownloadTaskWithRequest:requestprogress:nildestination:^NSURL*(NSURL*targetPath,NSURLResponse*response){
8.NSURL*documentsDirectoryURL=[[NSFileManagerdefaultManager]URLForDirectory:NSDocumentDirectoryinDomain:NSUserDomainMaskappropriateForURL:nilcreate:NOerror:nil];
9.return[documentsDirectoryURLURLByAppendingPathComponent:[responsesuggestedFilename]];
10.}completionHandler:^(NSURLResponse*response,NSURL*filePath,NSError*error){
11.NSLog(@"Filedownloadedto:%@",filePath);
12.}];
13.[downloadTaskresume];
3、创建一个上传文件的任务
[objc]view
plain
1.NSURLSessionConfiguration*configuration=[NSURLSessionConfigurationdefaultSessionConfiguration];
2.AFURLSessionManager*manager=[[AFURLSessionManageralloc]initWithSessionConfiguration:configuration];
3.
4.NSURL*URL=[NSURLURLWithString:@"http://example.com/upload"];
5.NSURLRequest*request=[NSURLRequestrequestWithURL:URL];
6.
7.NSURL*filePath=[NSURLfileURLWithPath:@"file://path/to/image.png"];
8.NSURLSessionUploadTask*uploadTask=[manageruploadTaskWithRequest:requestfromFile:filePathprogress:nilcompletionHandler:^(NSURLResponse*response,idresponseObject,NSError*error){
9.if(error){
10.NSLog(@"Error:%@",error);
11.}else{
12.NSLog(@"Success:%@%@",response,responseObject);
13.}
14.}];
15.[uploadTaskresume];
4、处理JSON或Plist响应
IOS应用在处理JSON和Plist响应的时候可以十分轻便将其转换成NSDictionary对象或者NSArray对像,AFHTTPRequestOpeartionManager默认就可以处理JSON或Plist响应,也就是说当我们response.MIMEType为appication/json、text/json,AFHTTPRequestOpeartionManager默认就可以处理,无需再次指定服务器响应解析器。
[objc]view
plain
1.
2.AFHTTPRequestOperationManager*manager=[AFHTTPRequestOperationManagermanager];
3.//manager.responseSerializer=[AFHTTPResponseSerializerserializer];
4.NSDictionary*parameter=@{@"location":@"长沙",@"output":@"json",@"ak":@"jlflVx1VTUahj05Q7GfB7PCf"};
5.[managerGET:@"http://api.map.baidu.com/telematics/v3/weather?"parameters:parametersuccess:^(AFHTTPRequestOperation*operation,idresponseObject){
6.NSLog(@"OK");
7.dic=responseObject;
8.NSArray*keys=[dicallKeys];
9.NSLog(@"%@",keys);
10.//_datas=responseObject;
11.//NSString*stringData=[[NSStringalloc]initWithData:_datasencoding:NSUTF8StringEncoding];
12.//NSLog(@"%@",stringData);
13.
14.}failure:^(AFHTTPRequestOperation*operation,NSError*error){
15.NSLog(@"NOTOK");
16.}];
相关文章推荐
- 组合数的计算
- ZeroC Ice 安装
- 双向循环链表
- 老程序员应该记住的5件事
- 稀土掘金
- iOS9 http & https
- 排排站
- hdu 1482
- 局域网不能访问 CentOS 的端口解决方案
- 抛弃jQuery 深入原生的JavaScript
- ASP.NET MVC 4 中的JSON数据交互
- cocos2d 制作动态光晕效果基础 —— blendFunc
- 在SQL Server中为什么不建议使用Not In子查询
- <html:text> Id属性
- Idea 使用中碰到的问题
- CentOS 安装 SonarQube
- MongoDB for循环插入数据至死循环问题
- 关于用NSRegularExpression来找出表情和网址
- 职场必须要会的餐桌礼仪
- STM32的GPIO口的8种配置模式