OC,oc語言
##NSURLRequest
NSURLRequest封裝了一次網路請求所需要的資料,主要封裝了以下資訊:
- 請求路徑(URL)
- 要求方法(GET或POST)
- 要求標頭
- 請求體
- 逾時參數
NSURLRequest與其子類NSMutableURLRequest
- NSURLRequest的所有的請求資訊拼接在請求路徑(URL)的後面
- NSMutableURLRequest的請求路徑與其他的請求資訊分開,其他請求資訊通過對應的Key對請求對象進行設定
- NSURLRequest通常用於GET請求
- NSMutableURLRequest通常用於POST請求
NSURLRequest封裝一次網路請求的的步驟
//1.建立請求路徑NSString *strURL = [NSString stringWithFormat:@"(此處為URL)/login?username=%@&pwd=%@", @"使用者名稱", @"密碼"];NSURL *url = [NSURL URLWithString:];//2.根據請求路徑封裝請求NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSMutableURLRequest封裝一次網路請求的的步驟
//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;
##NSURLConnection
NSURLConnection發送請求的步驟
- 建立請求路徑(NSURL)
- 將請求路徑封裝成請求對象(NSURLRequest),設定其他請求參數
- 使用NSURLConnection發送同步/非同步請求
NSURLConnection的代理
NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error/***遇到錯誤的時候調用,請求終止*/
NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response/***接收到伺服器響應的時候調用*response的中包含了伺服器的響應資訊,比較有價值是此次請求的資料的總長度*/- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data/***接收到伺服器的資料的時候調用,若資料較多會多次調用*通常在該方法中對伺服器返回的資料進行儲存*也可以在該方法中計算下載進度*/- (void)connectionDidFinishLoading:(NSURLConnection *)connection/***資料載入完畢的時候調用*/
NSURLConnectionDownloadDelegate
- (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檔案夾中,該檔案夾中的資料會被系統定時刪除*所以該方法必須實現,用於將改變資料的儲存位置*/
NSURLConnection的請求方式
同步請求(線程會被阻塞)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];/***data:伺服器返回的資料,即請求的資料*request:請求請求對象*response:伺服器的響應資料*error:錯誤資訊*/
非同步請求
//方法一(block)[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { /** *請求完成回調的block,參數的含義與銅鼓請求相同 */}];//方法二(代理)[NSURLConnection connectionWithRequest:request delegate:self]/***自動發送請求*/NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];/***需要手動發送請求*/
##URL中的中文處理
PS.在Xcode7中,NSURLConnection已經廢除了,不能再使用,現在使用的NSURLSession進行代替