概括:HTTP請求可以使用NSURLConnection、NSURLSession、AFN、ASI等方式實現,其中又包括了get、post兩種請求方式和同步、異步兩種程序執行方式。
NSURLConnection
1 get方式的同步請求
/** * get同步請求 */ -(void) getSynch{ // 獲取URL NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login?username=123&password=123"]; // 獲取request請求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 發送同步請求 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // 將data轉換成string NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"data -- %@", result); }
2 get方式的異步請求
/** * get異步請求 */ -(void) getAsynch{ // 獲取URL NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"]; // 獲取request請求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 發送同步請求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 將data數據轉成字典 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"data -- %@", dict); }]; }
3 post同步請求
/** * post同步請求 */ -(void) postSynch{ // 獲取URL NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer"]; // 設置post請求需要使用NSMutableURLRequest NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 設置請求方式為post (必選) request.HTTPMethod = @"POST"; // 發送同步請求 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // 將data轉換成string NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"data -- %@", result); }
4 post異步請求
/** * post異步請求 */ -(void) postAsynch{ // 獲取URL NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login"]; // 獲取request請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 設置請求方式為post request.HTTPMethod = @"POST"; // 設置表單參數 (可選) NSString *params = [NSString stringWithFormat:@"username=123&pwd=123"]; request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // 設置超時(可選) request.timeoutInterval = 5; // 設置請求頭信息(可選) [request setValue:@"iPhone 6" forHTTPHeaderField:@"User-Agent"]; // 設置post請求需要使用NSMutableURLRequest [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 將data數據轉成字典 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"data -- %@", dict); }]; }
NSURLSession
1 session的get請求
/** * session的get請求 */ -(void) sessionGet{ // 獲取一個session實例 NSURLSession *session = [NSURLSession sharedSession]; // 獲取url NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"]; // 創建一個數據訪問任務 NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"data -- %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; // 啟動任務,開始、回復都用resume [task resume]; }
2 session的post請求
/** * session的post請求 */ -(void) sessionPost{ // 獲取一個session實例 NSURLSession *session = [NSURLSession sharedSession]; // 獲取url NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login"]; // 獲取request請求對象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 設置請求方式 request.HTTPMethod = @"POST"; // 設置請求體, NSString *params = @"username=123&pwd=123"; request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // 創建一個數據訪問任務 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"data -- %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; // 開始任務 [task resume]; }
AFNetwork框架,需要導入 #import "AFNetworking.h"
1 AFN的get請求
#import "AFNetworking.h"
/** * afn的get請求 */ -(void) afnGet{ // 創建一個請求操作管理者 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 聲明響應結果不進行json、xml等格式解析,直接返回data manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 設置請求參數(可選) NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@"username"] = @"123"; params[@"pwd"] = @"123"; // 發送get請求 NSString *url = @"http://localhost:8070/MJServer/login"; [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 請求成功在這里處理 // 將響應數據轉換成字典 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dict); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 如果請求失敗在這里處理 NSLog(@"request fail"); }]; }
2 AFN的post請求
/** * afn的post請求 */ -(void) afnPost{ // 創建一個請求操作管理者 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 聲明響應結果不進行json、xml等格式解析,直接返回data manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // 設置請求參數(可選) NSMutableDictionary *params = [NSMutableDictionary dictionary]; params[@"username"] = @"123"; params[@"pwd"] = @"123"; // 發送get請求 NSString *url = @"http://localhost:8070/MJServer/login"; [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) { // 請求成功在這里處理 // 將響應數據轉換成字典 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", dict); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { // 如果請求失敗在這里處理 NSLog(@"request fail"); }]; }
ASI(注意添加libz類庫並修改ASI源文件為非arc)
1 ASI的get同步請求
#import "ASIHTTPRequest.h"
/** * ASI的get同步請求 */ -(void) asiGetSynch{ // 獲取url NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"]; // 獲取asi請求對象 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; // 發送同步請求 [request startSynchronous]; NSError *error = [request error]; if (error) { NSLog(@"請求失敗"); }else{ // NSString *data = [request responseString]; NSData *data = [request responseData]; NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"result -- %@", result); } }
2 ASI的get異步請求
/** * ASI的get異步請求 * 須知:ASI監聽請求過程有delegate、block和selector三種方式, * 經測試發現,delegate和block可以同時執行,selector和block也可以同時執行,但delegate和selector共存時(包括三者共存)不執行delegate * 執行順序:delegate > selector > block * 通過responseData和responseString獲取不到數據 * 使用了代理就不能直接通過responseData和responseString獲取到數據 */ -(void) asiGetAsynch{ // 獲取url NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/video"]; // 獲取asi請求對象 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; // 設置ASIHTTPRequestDelegate代理。 request.delegate = self; // 發送異步請求 [request startAsynchronous]; // 設置監聽請求過程的block [request setStartedBlock:^{ NSLog(@"block請求開始"); }]; [request setDataReceivedBlock:^(NSData *data) { NSLog(@"block獲得請求數據 -- %@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]); }]; [request setCompletionBlock:^{ NSLog(@"block請求結束"); }]; // 設置監聽請求過程的selector [request setDidStartSelector:@selector(start:)]; [request setDidReceiveDataSelector:@selector(receiveData:)]; [request setDidFinishSelector:@selector(finish:)]; } #pragma mark selector監聽方法 -(void)start:(ASIHTTPRequest *)request{ NSLog(@"selector請求開始"); } -(void) receiveData:(ASIHTTPRequest *) request{ // 這里獲取不到數據 NSLog(@"selector獲得請求數據 -- %@", [request responseString]); } -(void)finish:(ASIHTTPRequest *)request{ NSLog(@"selector請求結束"); } #pragma mark 實現ASIHTTPRequestDelegate的代理方法 - (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{ NSLog(@"delegate獲得請求數據 -- %@", [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]); } - (void)requestStarted:(ASIHTTPRequest *)request{ NSLog(@"delegate請求開始"); } - (void)requestFinished:(ASIHTTPRequest *)request{ NSLog(@"delegate請求結束"); } - (void)requestFailed:(ASIHTTPRequest *)request{ NSLog(@"delegate請求失敗"); }
3 ASI的post異步請求
#import "ASIFormDataRequest.h"
/** * ASI的post異步請求 */ -(void) asiPostAsynch{ // 獲取url NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:8070/MJServer/login"]; // 獲取ASI表單請求對象 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; // 設置請求參數 [request setPostValue:@"123" forKey:@"username"]; [request setPostValue:@"123" forKey:@"pwd"]; // 使用了代理就不能直接通過responseData和responseString獲取數據 // request.delegate = self; // 發送異步請求 [request startAsynchronous]; // 設置監聽(這里只演示block方法) __weak ASIFormDataRequest *req = request; [request setCompletionBlock:^{ NSLog(@"selector獲得請求數據 -- %@", [req responseString]); }]; }