您的位置:首页 > 理论基础 > 计算机网络

【iOS】网络操作与AFNetworking

2015-10-15 10:25 405 查看
一 AFNetworking 简介

AFNetworking是一个 在IOS开发中 使用非常多网络开源库,适用于iOS以及Mac OS X. 它构建于在(apple ios开发文档) NSURLConnection , NSOperation , 以及其他熟悉的Foundation技术之上。它拥有良好的架构,丰富的api,以及模块化构建方式,使得使用起来非常轻松.




AFURLConnectionOperation :继承自 NSOperation 实现了NSURLConnection 的代理方法.

AFHTTPRequestOperation : 继承自 AFURLConnectionOperation的子类,当request请求使用的协议为HTTP和HTTPS时使用,它封装了用于 决定request是否成功的状态码和内容类型.

AFJSONRequestOperation : 继承自AFHTTPRequestOperation,用于下载和处理json response数据.

AFXMLRequestOperation : 继承自 AFHTTPRequestOperation,用于下载和处理xml response数据.

AFPropertyListRequestOperation : 继承自 AFHTTPRequestOperation,用于下载和处理 property
list response数据.

AFHTTPClient :是一个封装了基于http协议的网络应用程序的公共交流模式.包含

1.发起 基于根路径的使用基本的url相关路径来只做request

2.为request自动添加设置http headers.

3.使用http 基础证书或者OAuth来验证request

4.为由client***的requests管理一个NSOperationQueue

5.从NSDictionary生成一个查询字符串或http bodies.

6.从request中构建多部件

7.自动的解析http response数据为相应的表现数据

8.在网络可达性测试用监控和响应变化.

注: 官方使用文档说明: http://cocoadocs.org/docsets/AFNetworking/1.3.0/

二 加载到开发环境中

1.下载AFNetworking

https://github.com/AFNetworking/AFNetworking

2.解压后将AFNetWorking文件夹拖入项目工程中去







3.添加SystemConfiguration和MobileCoreServices 框架





4.在预编译头文件中添加相关的头文件

#ifdef __OBJC__

#import <UIKit/UIKit.h>

#import <Foundation/Foundation.h>

#import <SystemConfiguration/SystemConfiguration.h>

#import <MobileCoreServices/MobileCoreServices.h>

#endif

注意:该类库需要在 ARC 的环境下 ,在非ARC 的工程中 ,添加 -fobjc-arc

四 使用代码

详见: https://github.com/ZhangzheBJUT/IOSProject/tree/master/NetworkTool

ZZUtilNetWork.h和ZZUtilNetWork.m是对 AFNetworking 使用简单封装。
五 小结
AFNetworking的基础部分是 AFURLConnectionOperation,它是一个 NSOperation subclass,网络部分由 NSURLConnection 完成,实现了 NSURLConnection 相关的代理方法,然后利用 NSOperation 的 state (isReady→isExecuting→isFinished) 变化来进行网络控制。网络请求是在一个指定的线程(networkRequestThread)完成。

AFURLConnectionOperation 是一个很纯粹的网络请求 operation,可以对他进行 start/cancel/pause/resume 操作,可以获取对应的 NSURLRequest 和 NSURLResponse 数据。支持 NSInputStream/NSOutputStream,提供了 uploadPress 和 downloadProgress 以方便其他使用。

AFHTTPRequestOperation 是 AFURLConnectionOperation 的子类,针对 HTTP+HTTPS 协议做了一层封装,比如 statusCode、Content-Type 等,添加了请求成功和失败的回调 block,提供了 addAcceptableContentTypes: 以方便上层使用。

代码样例:

众所周知,苹果搞的一套框架NSContention发送请求与接收请求的方式十分繁琐。操作起来很不方便。不仅要做区分各种请求设置各种不同的参数,而且还要经常在多线程里操作,同时还要对请求与返回的数据做各种序列化的操作,同时还要考虑请求数据的安全等一堆问题。

一、早前的几个网络框架

1、ASI框架: HTTP终结者.很牛, 但是有BUG, 已经停止更新.
2、MKNetworkKit (印度人写的).
3、AFN一直还在更新.

AFNetworking的出现:MAC/iOS设计的一套网络框架.(为了简化网络操作)

地址:https://github.com/AFNetworking/AFNetworking

*AFN专注与网络数据传输,以及网络中多线程的处理.

二、AFNetworking的使用

1、AFN特性 :

*登录传参数时,传递字典即可.(键名为参数名,键值为参数值).

*自动到子线程中执行,执行完后返回主线程.

*返回的结果自动序列化为NSDictionary.

2、使用AFN注意 :

*AFHTTPRequestOperationManager封装了通过HTTP协议与Web应用程序进行通讯的常用方法.(这个实例化的时候不是单例, 因为没有shared字)

*包括创建请求/响应序列化/网络监控/数据安全.

*方法等都是以AF开头的.

3、AFN能做的 (网络中的都涵盖了):

*GET/POST/PUT/DELETE/HEAD请求.

*JSON数据解析/Plist数据解析.(不支持XML数据解析)

*POSTJSON.

*上传/下载.

4、使用步骤 : (可参考说明文档)

1.首先需要实例化一个请求管理器AFHTTPRequestOperationManager.

2.设置请求的数据格式:默认是二进制.(不是可改)

*AFHTTPRequestSerializer(二进制)

*AFJSONRequestSerializer(JSON)

*AFPropertyListRequestSerializer(Plist)

3.设置响应的数据格式:默认是JSON.(不是可改)

*AFHTTPResponseSerializer(二进制)

*AFJSONResponseSerializer(JSON)

*AFPropertyListResponseSerializer(Plist)

*AFXMLParserResponseSerializer(XML)

*AFImageResponseSerializer(Image)

*AFCompoundResponseSerializer(组合的)

4.如果响应者的MIMEType不正确,就要修改acceptableContentTypes.

5.调用方法,发送响应的请求(GET/POST...).

关于修改AFN源码:通常序列化时做对text/plan等的支持时,可以一劳永逸的修改源代码,在acceptableContentTypes中修改即可。

AFN进行GET、POST登录:

[objc] view
plaincopy

#pragma mark - get/post登录

- (void)getLogin {

//1.管理器

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];



//2.设置登录参数

NSDictionary *dict = @{ @"username":@"xn", @"password":@"123" };



//3.请求

[manager GET:@"http://localhost/login.php" parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"GET --> %@, %@", responseObject, [NSThread currentThread]); //自动返回主线程

} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"%@", error);

}];

}



/**

* 和上面的GET用法完全一样, 只有一个POST参数不一样

*/

- (void)postLogin {

//1.管理器

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];



//2.设置登录参数

NSDictionary *dict = @{ @"username":@"xn", @"password":@"123" };



//3.请求

[manager POST:@"http://localhost/login.php" parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"POST --> %@, %@", responseObject, [NSThread currentThread]); //自动返回主线程

} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"%@", error);

}];

}

AFN进行网络数据解析,获取Plist,JSON,XML(AFN不支持自动解析XML,有专门的框架去做,如SAX,PULL,KissXML等)

[objc] view
plaincopy

#pragma mark - get 数据解析

- (void)getJSON {

//1.请求管理器

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];



//2.发起请求

[manager GET:@"http://localhost/videos.json" parameters:nil success: ^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"%@", responseObject);

} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"%@", error);

}];

}



/**

* 不支持XML数据解析

*/

- (void)getXML {

//1.管理器

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];



//2.设置返回数据类型

manager.responseSerializer = [AFXMLParserResponseSerializer serializer]; //先实例化一下



//3.发起请求

[manager GET:@"http://localhost/videos.xml" parameters:nil success: ^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"%@", responseObject);

} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"%@", error);

}];

}



- (void)getPlist {

//1.管理器

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];



//2.设置response类型

manager.responseSerializer = [AFPropertyListResponseSerializer serializer]; //是Response, 别写成request了. 修改为plist类型.

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"]; //这个可以直接往框架里面修改.



//3.请求

[manager GET:@"http://localhost/videos.plist" parameters:nil success: ^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"%@", responseObject);

} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"%@", error);

}];

}

用AFN来POST JSON数据,上传、下载等。(上传、下载主页说明上有https://github.com/AFNetworking/AFNetworking

[objc] view
plaincopy

#pragma mark - post json数据与上传文件等

- (void)postJSON {

//1.管理器

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];



//2.设定类型. (这里要设置request-response的类型)

manager.requestSerializer = [AFJSONRequestSerializer serializer];

manager.responseSerializer = [AFHTTPResponseSerializer serializer]; //这个决定了下面responseObject返回的类型

// manager.responseSerializer = [AFJSONResponseSerializer serializer];

// manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];



//2.设置登录参数

NSDictionary *dict = @{ @"username":@"xn", @"password":@"123" };



//3.发送请求

[manager POST:@"http://localhost/postjson.php" parameters:dict success: ^(AFHTTPRequestOperation *operation, id responseObject) {

// NSLog(@"postjson--> %@", responseObject); //这样显示JSON的话需要设置text/plain

NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

NSLog(@"%@",result);

} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {

NSLog(@"%@", error);

}];

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: