iOS開發ASIHTTPRequest直接讀取磁碟資料流請求體

來源:互聯網
上載者:User

本文為大家介紹了iOS開發ASIHTTPRequest直接讀取磁碟資料流的請求體的內容,其中包括ASIFormDataRequests,普通ASIHTTPRequest等等內容。

從0.96版本開始,ASIHTTPRequest可以使用磁碟上的資料來作為請求體。這意味著不需要將檔案完全讀入記憶體中,這就避免的當使用大檔案時的嚴重記憶體消耗。使用這個特性的方法有好幾種:ASIFormDataRequests和普通ASIHTTPRequest等等,下面來具體介紹。

ASIFormDataRequests

當使用setFile:forKey:時,ASIFormDataRequests自動使用這個特性。request將會建立一個包含整個post體的臨時檔案。檔案會一點一點寫入post體。這樣的request是由 CFReadStreamCreateForStreamedHTTPRequest建立的,它使用檔案讀取流來作為資源。

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

普通ASIHTTPRequest

如果你明白自己的request體會很大,那麼為這個request設定流式讀模數式。

 
  1. [request setShouldStreamPostDataFromDisk:YES]; 

下面的例子中,我們將一個NSData對象添加到post體。這有兩個方法:從記憶體中添加appendPostData:),或者從檔案中添加appendPostDataFromFile:);

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

這個例子中,我們想直接PUT一個大檔案。我們得自己設定setPostBodyFilePath ,ASIHTTPRequest將使用這個檔案來作為post體。

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

IMPORTANT:切勿對使用上述函數的request使用setPostBody——他們是互斥的。只有在你要自己建立request的請求體,並且還準備在記憶體中保持這個請求體時,才應該使用setPostBody。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.