一.HTTP协议
1.http 协议的看法
http协议的全称是超文本传输协议,定制传输数据的规范(客户端与服务器之间的数据传输规范)
2.通讯过程
<1>请求
* 客户端-->服务器
请求内容
a,请求行(请求方法/请求资源路径/http协议版本)
b,请求头(客户端的信息)
c,请求体(post请求才需要有,存放具体数据)
* 比如文件数据
* post
请求的参数数据
<2>响应
服务器-->客户端
响应的内容
a,状态行,响应行(http协议版本/状态码/状态信息)
b,响应头(服务器信息,返回数据类型,返回数据长度)
c,实体内容(返回给客户端的具体内容,也成响应体)
*比如服务器返回的json数据
*比如服务器返回的文件数据
3.请求方法
<1>GET
*参数都拼接到URL后面
*参数有限制
<2>post
*参数都在请求体
*参数没有限制
*文件上传只能用post
<3>head:获得响应头信息,不获取响应体
4.iOS中发送请求的手段
<1>NSURLConnection
*苹果原生
*使用起来较复杂
<2>ASI
*基于CFNetwork
*提供强大功能,用起来较为简单
<3>AFN
*基于NSURLConnection
*提供简单的功能,使用简单
二,NSURLConnection
1.发送请求
<1>发送同步请求
+ (NSData*)sendSynchronousRequest:(NSURLRequest *)requestreturningResponse:(NSURLResponse **)response error:(NSError **)error;
<2>发送一步请求(Block)
+ (void)sendAsynchronousRequest:(NSURLRequest*)request
queue:(NSOperationQueue*)queue
completionHandler:(void (^)(NSURLResponse*response, NSData* data, NSError* connectionError)) handler);
<3>发送一步请求(代理方法)
自动开启
[NSURLConnectionconnectionWithRequest:request delegate:self];
[[NSURLConnectionalloc]initWithRequest:request delegate:self];
[NSURLConnectionalloc]initWithRequest:request delegate:self startImmediately:NO];
手动开启
NSURLConnection *conn =[NSURLConnection connectionWithRequest:request delegate:self];
[conn start];
2.文件下载(大文件下载)
<1>实现方案:边下载边写入(写到沙盒的某个文件中)
<2>具体步骤
a.在接收到服务器的响应时
//创建一个空文件-NSFileManager
[mgrcreateFileAtPath:filepath contents:nil attributes:nil];
//创建一个跟空文件相关联的句柄对象-NSFileHandle
[NSFileHandlefileHandleForWritingAtPath:filepath];
b.在接收到服务器的数据时
//利用句柄对象将服务器放回数据卸任文件尾部
//移动到文件尾部
[self.writeHandleseekToEndOfFile];
//从当前位置写入数据
[self.writeHandlewriteData:data];
c.在接收完数据库返回的数据时
//关闭句柄
[self.writeHandle closeFile];
self.writeHandle = nil;
3.断点下载
关键技术点:设置请求头range,告诉服务器下载那一段
4.文件上传
<1>明确
只能用post请求,请求参数都在请求体中(文件参数/非文件类型的普通参数)
<2>实现步骤
a.拼接请求体(文件参数/非文件类型的普通参数)
*文件参数
//参数描述
content-disposition:form-data;name="参数名";filename="文件名"\r\n
//文件类型
content type:文件的类型\r\n
//文件的二进制数据
\r\n
文件的二进制数据
\r\n
*非文件参数、
//参数开始标记
--zz\r\n
//参数描述
content-disposition:form-data;name="参数名"\r\n
//参数值
\r\n
参数值
\r\n
//参数结束标记
--zz--\r\n
b.设置请求头
请求体的长度
content-length:请求体长度(字节长度)
请求题类型
content-type:
//普通post请求:application/x-www-form-urlencoded
//上传文件的post请求:multipart/form-data;boundary--zz
三、NSURLCache
缓存的使用步骤
//回去全局缓存对象
NSURLCache *cache = [NSURLCachesharedURLCache];
//设置缓存容量(默认为512)
cache.memoryCapacity=1024*1024;
cache.diskCapacity=20*1024*1024;
//设置缓存策略
request.cachePolicy =NSURLRequestReturnCacheDataElseLoad;
四、ASI
1.缓存的使用步骤
<1>缓存单个请求
// 2获得系统默认的缓存管理对象(决定着缓存存储路径)
ASIDownloadCache *cache =[ASIDownloadCache sharedCache];
// 默认的缓存加载策略 :不读取缓存
cache.defaultCachePolicy =ASIDoNotReadFromCacheCachePolicy;
// 3.使用缓存
request.downloadCache =cache;
// 缓存加载策略
request.cachePolicy =ASIOnlyLoadIfNotCachedCachePolicy;
// 缓存存储策略
request.cacheStoragePolicy =ASICachePermanentlyCacheStoragePolicy;
<2>缓存所有请求
//2.获得系统默认的缓存管理对象(决定着缓存存储路径)
ASIDownloadCache *cache =[ASIDownloadCache sharedCache];
// 缓存加载策略
cache.defaultCachePolicy =ASIOnlyLoadIfNotCachedCachePolicy;
// 3.设置cache为全局缓存
[ASIHTTPRequestsetDefaultCache:cache];
2.发送请求
<1>同步请求
[request startSynchronous];
<2>异步请求
[self.request startAsynchronous];
3.get/post
<1>get
ASIHTTPRequest *request =[ASIHTTPRequest requestWithURL:url];
<2>post
ASIFormDataRequest *request= [ASIFormDataRequest requestWithURL:url];
// 2.添加请求参数(请求体中的参数)
[request setPostValue:@"123" forKey:@"username"];
[request setPostValue:@"999" forKey:@"pwd"];
4.文件下载
// 1.创建请求对象
NSURL *url = [NSURLURLWithString:@"http://--------"];
ASIHTTPRequest *request =[ASIHTTPRequest requestWithURL:url];
// 2.设置所下载文件的存储路径
NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filepath = [cachestringByAppendingPathComponent:@"jre.zip"];
request.downloadDestinationPath= filepath;
// 3.设置下载代理
request.downloadProgressDelegate= self.circleView;
// 4.支持断点下载
request.allowResumeForFileDownloads= YES;
// 5.发送请求
[request startAsynchronous];
5.文件上传
// 1.创建请求
NSURL *url = [NSURLURLWithString:@"http://=-------"];
ASIFormDataRequest *request= [ASIFormDataRequest requestWithURL:url];
// 2.设置(指定)所要上传文件的路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [cachesstringByAppendingPathComponent:@"jre.zip"];
[request setFile:fileforKey:@"file"];
([requestsetFile:file withFileName:@"123.txt" andContentType:@"text/plain" forKey:@"file"];
[request setData:datawithFileName:@"minion.png" andContentType:@"image/png" forKey:@"file"];
)
// 3.设置其他请求参数
[request setPostValue:@"zhangsan" forKey:@"username"];
// 设置代理监听上传进度
request.uploadProgressDelegate= self.circleView;
// 4.发送请求
[request startAsynchronous];
// 程序进入后台, 继续发送请求
request.shouldContinueWhenAppEntersBackground= YES;
6.监听请求过程
<1>代理方法
- (void)requestStarted;
- (void)requestReceivedResponseHeaders:(NSDictionary*)newHeaders;
- (void)requestFinished;
- (void)failWithError:(NSError*)theError;
<2>SEL
request.delegate=self;
[requestsetDidStartSelector:@selector(start)];
----
----
----
<3>Block
[request setStartedBlock:^{
}];
----
-----
7.通过request对象获取服务器响应
<1>获得响应头信息
@property (nonatomic, retain) NSDictionary*responseheader;
<2>获得响应体
//将二进制数据转换成字符串
- (NSString *)responseString;
// 直接返回二进制数据
- (NSData *)responseData;
五、AFN
1. get/post
<1>get
// 1.获得请求管理者
AFHTTPRequestOperationManager*mgr = [AFHTTPRequestOperationManager manager];
// 2.发送GET请求
[mgr GET:@"http://-------" parameters:nil
success:^(AFHTTPRequestOperation *operation,NSDictionary *dict) { // responseObject : 在这种情况下是字典
NSLog(@"请求成功---%@", dict);
}
failure:^(AFHTTPRequestOperation *operation,NSError *error) {
NSLog(@"请求失败---%@", error);
}];
<2>post
// 1.获得请求管理者
AFHTTPRequestOperationManager*mgr = [AFHTTPRequestOperationManager manager];
mgr.responseSerializer =[AFXMLParserResponseSerializer serializer];
// 2.发送POST请求
[mgr POST:@"http://192.168.1.200:8080/MJServer/video" parameters:@{@"type" : @"XML"}
success:^(AFHTTPRequestOperation *operation,NSXMLParser *parser) {
}
failure:^(AFHTTPRequestOperation *operation,NSError *error) {
NSLog(@"请求失败---%@", error);
}];
2.文件上传
// 1.获得请求管理者
AFHTTPRequestOperationManager*mgr = [AFHTTPRequestOperationManager manager];
// 2.发送请求(做文件上传)
// parameters : 只能放非文件参数
NSMutableDictionary *params = [NSMutableDictionarydictionary];
params[@"username"] = @"zhangsan";
[mgr POST:@"http://--------" parameters:params
constructingBodyWithBlock:^(id<AFMultipartFormData>formData) {
// 一定要在这个block中添加文件参数
// 加载文件数据
NSString *file = [[NSBundle mainBundle]pathForResource:@"test.txt" ofType:nil];
NSData *data = [NSDatadataWithContentsOfFile:file];
// 拼接文件参数
[formData appendPartWithFileData:data name:@"file" fileName:@"123.txt" mimeType:@"text/plain"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"上传成功----%@", responseObject);
} failure:^(AFHTTPRequestOperation*operation, NSError *error) {
NSLog(@"上传失败----%@", error);
}];
六、网络状态监控
<1>Reachability
//监听网络状态改变通知
[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(networkStateChange)name:kReachabilityChangedNotification object:nil];
//创建Reachability
Reachability *conn =[Reachability reachabilityForInternetConnection];
//开启监控
[self.conn startNotifier];
// 2.检测手机是否能上网络(WIFI\3G\2.5G)
- (void)networkStateChange
{
// 1.检测wifi状态
Reachability *wifi = [ReachabilityreachabilityForLocalWiFi];
// 2.检测手机是否能上网络(WIFI\3G\2.5G)
Reachability *conn = [ReachabilityreachabilityForInternetConnection];
// 3.判断网络状态
if ([wifi currentReachabilityStatus] !=NotReachable) { // 有wifi
NSLog(@"有wifi");
} elseif ([conn currentReachabilityStatus]!= NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
NSLog(@"使用手机自带网络进行上网");
} else { // 没有网络
NSLog(@"没有网络");
}
}
<2>AFN
// 1.获得网络监控的管理者
AFNetworkReachabilityManager*mgr = [AFNetworkReachabilityManager sharedManager];
// 2.设置网络状态改变后的处理
[mgrsetReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 当网络状态改变了, 就会调用这个block
switch (status) {
caseAFNetworkReachabilityStatusUnknown: // 未知网络
NSLog(@"未知网络");
break;
caseAFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
NSLog(@"没有网络(断网)");
break;
caseAFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
NSLog(@"手机自带网络");
break;
caseAFNetworkReachabilityStatusReachableViaWiFi: // WIFI
NSLog(@"WIFI");
break;
}
}];
// 3.开始监控
[mgr startMonitoring];
七、ASI,AFN有什么区别
1.性能
*ASI基于CFNetwork
*AFN基于NSURLConnection
*运行性能;ASI>AFN
2.处理服务器数据
*AFN:根据服务器返回数据自动解析
json数据自动转成NSDictionary,NSArray
xml数据自动转成NSXMLParser
*ASI:直接返回NSDate二进制数据
3.处理请求的过程
*ASI:三种(代理\SEL\Block)
*AFN:两个Block
4.ASI的特色
<1>缓存
<2>下载
*轻松监听请求进度
*轻松实现断点下载
<3>提供很多扩展接口(比如数据的压缩)
ASIDataCompressor.h
ASIDataDecompressor.h
<4>ASIHTTPRequest继承自NSOperation
能用队列统一管理请求
请求之间能依赖
<5>ASINetworkQueue
统一管理所有请求
监听所有请求进度
监听所有请求的开始、失败、完毕
shouldCancelAllRequestsOnFailure
YES:一个请求失败,全部请求取消
NO:一个请求失败,不影响其他请求
5.AFN的特色
使用简单
自带网络监控