本文為大家介紹了iOS開發ASIHTTPRequest直接讀取磁碟資料流的請求體的內容,其中包括ASIFormDataRequests,普通ASIHTTPRequest等等內容。
從0.96版本開始,ASIHTTPRequest可以使用磁碟上的資料來作為請求體。這意味著不需要將檔案完全讀入記憶體中,這就避免的當使用大檔案時的嚴重記憶體消耗。使用這個特性的方法有好幾種:ASIFormDataRequests和普通ASIHTTPRequest等等,下面來具體介紹。
ASIFormDataRequests
當使用setFile:forKey:時,ASIFormDataRequests自動使用這個特性。request將會建立一個包含整個post體的臨時檔案。檔案會一點一點寫入post體。這樣的request是由 CFReadStreamCreateForStreamedHTTPRequest建立的,它使用檔案讀取流來作為資源。
- 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];
普通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。