ASIHTTPRequest-直接读取磁盘数据流的请求体

来源:互联网 发布:广电 知乎 编辑:程序博客网 时间:2024/06/05 03:49

从0.96版本开始,ASIHTTPRequest可以使用磁盘上的数据来作为请求体。这意味着不需要将文件完全读入内存中,这就避免的当使用大文件时的严重内存消耗。

使用这个特性的方法有好几种:

ASIFormDataRequests

NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];[request setPostValue:@"foo" forKey:@"post_var"];[request setFile:@"/Users/ben/Desktop/bigfile.txt" forKey:@"file"];[request startSynchronous];

当使用setFile:forKey:时,ASIFormDataRequests 自动使用这个特性。request将会创建一个包含整个post体的临时文件。文件会一点一点写入post体。这样的request是由CFReadStreamCreateForStreamedHTTPRequest创建的,它使用文件读取流来作为资源。

普通ASIHTTPRequest

如果你明白自己的request体会很大,那么为这个request设置流式读取模式。

[request setShouldStreamPostDataFromDisk:YES];

下面的例子中,我们将一个NSData对象添加到post体。这有两个方法:从内存中添加(appendPostData:),或者从文件中添加(appendPostDataFromFile:);

NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com/"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request setShouldStreamPostDataFromDisk:YES];[request appendPostData:myBigNSData];[request appendPostDataFromFile:@"/Users/ben/Desktop/bigfile.txt"];[request startSynchronous];

这个例子中,我们想直接PUT一个大文件。我们得自己设置setPostBodyFilePath ,ASIHTTPRequest将使用这个文件来作为post体。

NSURL *url = [NSURL URLWithString:@"http://www.dreamingwish.com"];ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request setRequestMethod:@"PUT"];[request setPostBodyFilePath:@"/Users/ben/Desktop/another-big-one.txt"];[request setShouldStreamPostDataFromDisk:YES];[request startSynchronous];

IMPORTANT:切勿对使用上述函数的request使用setPostBody——他们是互斥的。只有在你要自己建立request的请求体,并且还准备在内存中保持这个请求体时,才应该使用setPostBody。