如下:nginx
#pragma mark 同步GET方式下載圖片 downPath爲圖片路徑 - (void)downloadFileSync: (NSString *)downPath{ //建立URL對象 NSURL *url = [NSURL URLWithString:downPath]; //建立請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f]; NSURLResponse *responseData = nil;//應答數據 NSError *err = nil;//錯誤記錄 //發送網絡同步請求獲取遠程數據 NSData *imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseData error:&err]; NSLog(@"responseData: %@", responseData); if (err) { NSLog(@"err: %@", err); return; } //從網絡應答生成圖片,並顯示在imageView中 // self.imageToDisp.image = [UIImage imageWithData:imageData]; return; }
服務器返回的responseData爲:json
<NSHTTPURLResponse: 0x7fba496e3a80> 服務器
{ URL: http://edutohome-upload.stor.sinaapp.com/1433834502upload.png } 網絡
{ status code: 200, headers {app
"Accept-Ranges" = bytes;異步
"Cache-Control" = "max-age=7200";async
Connection = "keep-alive";函數
"Content-Length" = 43546;url
"Content-Type" = "image/png";spa
Date = "Tue, 09 Jun 2015 07:21:42 GMT";
Etag = 1db5335d9e6fef747fc9d35f78fe3c67;
Expires = "Tue, 09 Jun 2015 09:21:42 GMT";
"Last-Modified" = "Tue, 09 Jun 2015 07:21:42 GMT";
Server = "nginx/1.4.4";
"X-Sws-Timestamp" = "1433834502.42126";
"X-Trans-Id" = "tx5eb26269aa334a36a1153-0055769406";
} }
異步方式下載須要使用NSURLConnectionDataDelegate委託方法,分爲幾步:
發送異步鏈接請求
完成回調函數-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
完成回調函數-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
完成回調函數-(void)connectionDidFinishLoading:(NSURLConnection *)connection
#pragma mark 異步GET方式下載 - (IBAction)downMusic:(NSString *)downPath { //建立URL對象 NSURL *url = [NSURL URLWithString:downPath]; //建立請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f]; //發送異步鏈接請求 [NSURLConnection connectionWithRequest:request delegate:self]; } #pragma mark 得到服務器響應後調用該方法,僅調用一次 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ //建立存放圖片文件的對象 // self.data = [NSMutableData new]; //獲取mp3文件大小 // self.lenght = [response expectedContentLength]; } #pragma mark 接受到應答數據以後調用,會被屢次調用 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ //追加每次返回的數據至存放對象 // [self.data appendData:data]; // self.curLenght = [self.data length]; } #pragma mark 接收完成數據時調用 -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ //顯示/保存圖片 }
另外一種HTTP異步請求方式,採用POST,REST/JSON風格,並設置了Header和Body
NSURL *url = [NSURL URLWithString: [NSString stringWithFormat:@"%@", @"http://localhost:8080/register"]]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:3.0]; //設置POST方式 [request setHTTPMethod:@"POST"]; //設置Header: content-type [request setValue:@"application/json" forHTTPHeaderField:@"content-type"]; //設置Body NSDictionary *dict = @{@"name":@"Suares"}; [request setHTTPBody:nsData]; //異步代碼塊方式 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"執行代碼塊"); NSDictionary *dictResp = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSArray *dictItems = dictResp[@"items"]; NSString *status = dictResp[@"status"]; NSString *name = dictItems[0][@"name"]; //處理接收的數據,(注意在主線程中更新UI) dispatch_async(dispatch_get_main_queue(), ^{ self.myText.text = [NSString stringWithFormat:@"%@\n%@", status, name]; }); NSLog(@"請求完成!");