NSURLRequest封裝了一次網絡請求所需要的數據,主要封裝了以下信息:
NSURLRequest與其子類NSMutableURLRequest
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的代理
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中的中文通要進行處理,通常使用UTF-8編碼
//進行如下轉碼[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
新聞熱點
疑難解答