NSURLRequest 負責把「要怎麼請」這件事打包成一個物件,內容包含:
它與其子類 NSMutableURLRequest 的關鍵差異在於可變性:NSURLRequest 建立後不可修改,且所有資訊都拼在 URL 後面;NSMutableURLRequest 則把路徑與其他資訊分開,可以逐一透過對應的屬性設定,因此通常用於 POST 請求。實務上的分工大致是:NSURLRequest 用於 GET,NSMutableURLRequest 用於 POST。
// 1. 拼接請求路徑,參數直接接在 URL 後
NSString *strURL = [NSString stringWithFormat:@"(此處為 URL)/login?username=%@&pwd=%@",
@"用戶名", @"密碼"];
NSURL *url = [NSURL URLWithString:strURL];
// 2. 封裝成請求物件
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 1. 請求路徑不含參數 NSURL *url = [NSURL URLWithString:@"(此處為 URL)/login"]; // 2. 建立可變請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 3. 指定方法 request.HTTPMethod = @"POST"; // 4. 把參數放進請求本文 request.HTTPBody = [@"username=用戶名&pwd=密碼" dataUsingEncoding:NSUTF8StringEncoding]; // 5. 設定逾時秒數 request.timeoutInterval = 5;
順帶一提,GET 請求把帳密放在 URL 上會被伺服器日誌完整記錄,屬於不良實務。任何敏感資訊都應走 POST 並搭配 HTTPS。
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error // 遇到錯誤,請求終止
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response // 收到回應,response 中最有價值的是本次資料的總長度 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data // 收到資料;資料量大時會多次呼叫 // 可在此保存資料,或計算下載進度 - (void)connectionDidFinishLoading:(NSURLConnection *)connection // 資料載入完畢
- (void)connection:(NSURLConnection *)connection
didWriteData:(long long)bytesWritten
totalBytesWritten:(long long)totalBytesWritten
expectedTotalBytes:(long long)expectedTotalBytes
// 每次向沙盒寫檔都會呼叫
- (void)connectionDidResumeDownloading:(NSURLConnection *)connection
totalBytesWritten:(long long)totalBytesWritten
expectedTotalBytes:(long long)expectedTotalBytes
// 支援斷點續傳的核心方法
- (void)connectionDidFinishDownloading:(NSURLConnection *)connection
destinationURL:(NSURL *)destinationURL
// 檔案位於 tmp,該目錄會被系統週期性清理
// 因此必須實作此方法,把檔案移到長期保存的位置
會阻塞目前執行緒,在主執行緒呼叫會直接讓 UI 凍結,只適合在背景隊列中使用。
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// data:伺服器回傳的內容
// response:回應中繼資料
// error:錯誤資訊
// 方法一:Block 回呼
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 參數含義與同步版本相同
}];
// 方法二:delegate,會自動送出請求
[NSURLConnection connectionWithRequest:request delegate:self];
// 若要手動控制送出時機,startImmediately 傳 NO
NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:request
delegate:self
startImmediately:NO];
URL 只允許 ASCII 字元,中文必須先做百分比編碼,一般使用 UTF-8:
[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
實務上要留意,這個方法不會編碼 &、?、= 等保留字元。若你的參數值本身含有這些字元,改用 NSURLComponents 的 queryItems 讓系統代為處理會安全得多。
最後必須說明:NSURLConnection 自 iOS 9 起已被蘋果標記為 deprecated,新專案請一律改用 NSURLSession。理解 NSURLConnection 的 delegate 模型仍有價值,因為 NSURLSession 的設計思路完整承襲了它,只是把「連線」抽象成了「任務」。