iOS之NSURLConnection詳解(2)

來源:互聯網
上載者:User

標籤:des   style   blog   color   io   os   ar   for   sp   

 1 一、NSURLConnection 2 1.發送請求 3 1> 發送一個同步請求 4 + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error; 5  6 2> 發送一個非同步請求(block) 7 + (void)sendAsynchronousRequest:(NSURLRequest*) request 8 queue:(NSOperationQueue*) queue 9 completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;10 11 3> 發送一個非同步請求(代理方法)12 [NSURLConnection connectionWithRequest:request delegate:self];13 [[NSURLConnection alloc] initWithRequest:request delegate:self];14 [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];15 16 NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];17 [conn start];18 19 2.檔案下載(大檔案下載)20 1> 實現方案 : 邊下載邊寫入(寫到沙箱的某個檔案中)21 2> 具體實現步驟22 a. 在接收到伺服器的響應時23 // 建立一個空檔案 - NSFileManager24 [mgr createFileAtPath:self.destPath contents:nil attributes:nil];25 26 // 建立一個跟空檔案相關聯的控制代碼對象 - NSFileHandle27 [NSFileHandle fileHandleForWritingAtPath:self.destPath];28 29 b. 在接收到伺服器的資料時30 // 利用控制代碼對象將伺服器返回的資料寫到檔案的末尾31 // 移動到檔案的尾部32 [self.writeHandle seekToEndOfFile];33 // 從當前移動的位置(檔案尾部)開始寫入資料34 [self.writeHandle writeData:data];35 36 c. 在接收完伺服器返回的資料時37 // 關閉控制代碼38 [self.writeHandle closeFile];39 self.writeHandle = nil;40 41 3.斷點下載42 1> 關鍵技術點43 * 佈建要求頭Range, 告訴伺服器下載哪一段資料44 45 4.檔案上傳46 1> 明確47 * 只能用POST請求48 * 請求參數都在請求體(檔案參數\非檔案類型的普通參數)49 50 2> 實現步驟51 a. 拼接請求體(檔案參數\非檔案類型的普通參數)52 * 檔案參數53 // 參數的開始標記(分割線)54 --nihao\r\n55 // 參數描述(參數名...)56 Content-Disposition: form-data; name="參數名"; filename="檔案名稱"\r\n57 // 檔案類型58 Content-Type: 檔案的類型MIMEType\r\n59 // 檔案的位元據(參數值)60 \r\n61 檔案的位元據62 \r\n63 64 * 非檔案參數(普通參數)65 // 參數的開始標記(分割線)66 --nihao\r\n67 // 參數描述(參數名...)68 Content-Disposition: form-data; name="參數名"\r\n69 // 參數值70 \r\n71 參數值72 \r\n73 74 * 所有參數結束的標記75 --nihao--\r\n76 77 b. 佈建要求頭78 * 請求體的長度79 Content-Length : 請求體的長度(位元組長度)80 81 * 請求資料的類型82 Content-Type :83 // 普通POST請求: application/x-www-form-urlencoded84 // 上傳檔案的POST請求 : multipart/form-data; boundary=--nihao

 

iOS之NSURLConnection詳解(2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.