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

ASIHTTPRequest

2016-02-19 09:27 585 查看
网络下载的第三方库
*********

本库是mrc的,如果项目是arc 的需要混编(-fno
-objc - arc)

需要4个系统库

SystemConfiguration.framework

libz.1.2.5.dylib

CFNetwork.framework

MobileCoreServices.frame

*************************************************get请求***********************

最常用的是ASIHTTPRequest

这个比系统的库好用的多

**************

+ (id)requestWithURL:(NSURL *)newURL

用url初始化请求对象

请求对象的属性和方法特别多

用过三个

@synthesize tag;

id <</span>ASIHTTPRequestDelegate>
delegate;

- (void)startAsynchronous;

开始异步下载 对应的还有一个同步下载 但是几乎不用

他有两个常用的代理方法:

- (void)requestFinished:(ASIHTTPRequest *)request

- (void)requestFailed:(ASIHTTPRequest *)request

他没有下载数据的方法

- (NSData *)responseData;

- (NSString *)responseString;

下载的数据直接封装到这两个属性里了 一般用data
因为string可能出现乱码

****************

如果没有请求完 nc把正在加载的vc
pop出来的时候会把vc销毁 下载完成后就会找不到代理方法就会崩掉 所以
要重写dealloc 在dealloc中把request的代理和下载都取消掉

- (void)dealloc

{

[request
clearDelegatesAndCancel];

}

******

*************************************************post请求***********************

用asi的库 实现post

ASIFormDataRequest

这个类专门用来发post请求的

@interface ASIFormDataRequest
: ASIHTTPRequest <<span
class="s3">NSCopying>

实现post协议上传 用这个类 不需要设置头和长度 也不需要设置body 只要把要传的参数作为键值对通过setpostvalue函数设置一下就可以
再设置代理和开始异步下载 实现两个代理方法即可 跟ASIHTTPRequest其实差不多

+ (id)requestWithURL:(NSURL *)newURL

- (void)setPostValue:(id <<span
class="s3">NSObject>)value forKey:(NSString *)key

post1的方法

- (void)addData:(id)data withFileName:(NSString *)fileName
andContentType:(NSString *)contentType
forKey:(NSString *)key

post2的方法

- (void)setDelegate:(id)newDelegate

- (void)startAsynchronous

例:

POST1:

[request setPostValue:@“test” forKey:@"username"];

POST2

[request addData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"1"ofType:@"png"]] withFileName:@"1.png" andContentType:@"image/png" forKey:@"headimage"];

*********************************断点续传*************************************

asi提供了断点续传的功能

很好用 具体用法如下

request = [ASIHTTPRequest requestWithURL:[NSURLURLWithString:@"http://dl_dir.qq.com/qqfile/qq/QQforMac/QQ_V2.4.1.dmg"]];

request.delegate = self;

request.downloadProgressDelegate = self;

[request setDownloadDestinationPath:_filePath];

[request setTemporaryFileDownloadPath:[NSString stringWithFormat:@"%@_temp",_filePath]];

[request startAsynchronous];

[request cancelAuthentication];

遵守两个协议

@protocol ASIHTTPRequestDelegate
<<span class="s2">NSObject>

@protocol ASIProgressDelegate
<<span class="s2">NSObject>

常用代理方法:

- (void)setProgress:(float)newProgress;

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