1 // 2 // ViewController.m 3 // IOS_0129_HTTP請求 4 // 5 // Created by ma c on 16/1/29. 6 // Copyright © 2016年 博文科技. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import "MBProgressHUD+MJ.h" 11 12 @interface ViewController () 13 @property (weak, nonatomic) IBOutlet UITextField *textName; 14 @property (weak, nonatomic) IBOutlet UITextField *textPassword; 15 16 - (IBAction)btnlogin; 17 18 @end 19 20 @implementation ViewController 21 22 /* 23 24 1.發送HTTP請求的方法 25 1>在HTTP/1.1協議中,定義了8種發送HTTP請求的方法 26 GET,POST,OPTIONS,HEAD,PUT,DELETE,TRACE,CONNECT,PATCH 27 2>根據HTTP協議設計初衷,不同的方法對資源有不同的操作方式 28 PUT:增 29 DELETE:刪 30 POST:改 31 GET:查 32 3>最常用的是GET,POST(實際上GET,POST都能辦到增刪改查) 33 4>參數 - 傳遞給服務器的具體數據 34 35 2.GET和POST對比 36 1>GET和POST主要體現在數據傳遞上 37 a.GET在請求URL后面以?的形式加上發送給服務器的參數,多個參數之間用&隔開 38 b.URL后面跟的參數不能超過1KB 39 40 c.POST發送給服務器的參數全部放在請求體中 41 d.理論上,POST傳遞的數據量沒有限制(看服務器處理能力) 42 43 3.GET和POST選擇 44 1>傳遞大量數據只能用POST(文件上傳) 45 2>GET安全性比POST差,機密信息用POST 46 3>僅僅是索取數據(數據查詢)用GET 47 4>如果是增刪改查數據,建議用POST 48 49 4.HTTP通信過程 - 請求 50 1>HTTP協議規定:1個完整的由客戶端發送給服務器的HTTP請求包含以下內容 51 a.請求行:包含了請求方法、請求資源路徑、HTTP版本協議 52 b.請求頭:包含了對客戶端的環境描述、客戶端請求的主機地址等 53 Host:客戶端想訪問的服務器主機地址 54 User-Agent:客戶端類型,客戶端的軟件環境 55 Accept:客戶端所能接收的數據類型 56 Accept-Language:客戶端的語言環境 57 Accept-Encoding:客戶端所支持的數據壓縮格式 58 c.請求體:客戶端發送給服務器的具體數據 59 60 5.HTTP通信過程 - 響應 61 1>客戶端向服務器發送請求,服務器應當作出響應,即返回數據給客戶端 62 2>HTTP協議規定:1個完整的HTTP響應中應該包含以下內容 63 a.狀態行:包含了HTTP協議版本、狀態碼、狀態英文名稱 64 b.響應頭:包含了對服務器的描述、對返回數據的描述 65 Server:服務器的類型 66 Content-Type:返回的數據類型 67 Content-Length:返回的數據長度 68 Date:響應的時間 69 3>實體內容:服務器返回給客戶端的具體數據 70 4>常見響應狀態碼: 71 */ 72 73 - (void)viewDidLoad { 74 [super viewDidLoad]; 75 76 self.view.backgroundColor = [UIColor groupTableViewBackgroundColor]; 77 } 78 79 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 80 { 81 [self.view endEditing:YES]; 82 } 83 84 - (IBAction)btnlogin { 85 86 NSString *usernameText = self.textName.text; 87 if (usernameText.length == 0) { 88 [MBProgressHUD showError:@"請輸入賬號"]; 89 return; 90 } 91 self.textPassword.secureTextEntry = YES; 92 NSString *password = self.textPassword.text; 93 if (password.length == 0) { 94 [MBProgressHUD showError:@"請輸入密碼"]; 95 return; 96 } 97 //1.GET請求默認 98 // //創建一個NSURL:請求路徑 99 // NSString *strURL = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText,password]; 100 101 // //NSURL后面不能包含中文,得對中文進行轉碼 102 // strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 103 104 // NSURL *url = [NSURL URLWithString:strURL]; 105 // //創建一個請求 106 // NSURLRequest *request = [NSURLRequest requestWithURL:url]; 107 108 // 增加蒙板 109 [MBProgressHUD showMessage:@"正在拼命加載..."]; 110 111 //2.POST請求 112 NSString *strURL = @"http://localhost:8080/MJServer/login"; 113 NSURL *url = [NSURL URLWithString:strURL]; 114 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 115 116 //5s后請求超時(默認60s超時) 117 request.timeoutInterval = 5; 118 //設置請求方式 119 request.HTTPMethod = @"POST"; 120 //設置請求頭 121 [request setValue:@"iPhone6" forHTTPHeaderField:@"User-Agent"]; 122 123 //設置請求體 124 NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@",usernameText,password]; 125 //NSString -> NSData 126 request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding]; 127 128 //異步請求 129 [self sendAsyncWithRequest:request]; 130 131 } 132 //異步請求 133 - (void)sendAsyncWithRequest:(NSURLRequest *)request 134 { 135 NSOperationQueue *queue = [NSOperationQueue mainQueue]; 136 137 [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { 138 139 //隱藏蒙版 140 [MBProgressHUD hideHUD]; 141 NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response; 142 NSString *msg = [NSHTTPURLResponse localizedStringForStatusCode:resp.statusCode]; 143 NSLog(@"%ld %@ %@",resp.statusCode, msg, resp.allHeaderFields); 144 145 //這個block會在請求完畢的時候自動調用 146 if (connectionError || data == nil) { 147 [MBProgressHUD showError:@"請求失敗"]; 148 return; 149 } 150 //解析服務器返回的JSON數據 151 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; 152 NSString *error = dict[@"error"]; 153 if (error) { 154 [MBProgressHUD showError:error]; 155 } 156 else{ 157 NSString *success = dict[@"success"]; 158 [MBProgressHUD showSuccess:success]; 159 } 160 }]; 161 } 162 163 @end
