iOS開發實踐之GET和POST請求
GET和POST請求是HTTP請求方式中最最為常見的。在說請求方式之前先熟悉HTTP的通信過程:
請求
1、請求行 : 請求方法、請求路徑、HTTP協議的版本
GET /MJServer/resources/images/1.jpg HTTP/1.1
2、請求頭 : 客戶端的一些描述信息
Host: 192.168.1.111:8080 // 客戶端想訪問的服務器主機地址
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9) Firefox/30.0 // 客戶端的類型,客戶端的軟件環境
Accept: text/html, // 客戶端所能接收的數據類型
Accept-Language: zh-cn // 客戶端的語言環境
Accept-Encoding: gzip // 客戶端支持的數據壓縮格式
3、請求體 : POST請求才有這個東西
請求參數,發給服務器的數據
響應
1、狀態行(響應行): HTTP協議的版本、響應狀態碼、響應狀態描述
Server: Apache-Coyote/1.1 // 服務器的類型
Content-Type: image/jpeg // 返回數據的類型
Content-Length: 56811 // 返回數據的長度
Date: Mon, 23 Jun 2014 12:54:52 GMT // 響應的時間
2、 響應頭:服務器的一些描述信息
Content-Type : 服務器返回給客戶端的內容類型
Content-Length : 服務器返回給客戶端的內容的長度(比如文件的大小)
3、 實體內容(響應體)
服務器返回給客戶端具體的數據,比如文件數據
NSMutableURLRequest(注意:非NSURLRequest 因為這個對象是不可變的)
1、設置超時時間(默認60s)
request.timeoutInterval = 15;
2、設置請求方式
request.HTTPMethod = @"POST";
3、設置請求體
request.HTTPBody = data;
4、設置請求頭 例如如下是傳JSON數據的表頭設置
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
GET和POST對比:
GET(默認情況是get請求):
特點:GET方式提交的參數直接拼接到url請求地址中,多個參數用&隔開。例如:http://localhost:8080/myService/login?username=123&pwd=123
缺點:
1、在url中暴露了所有的請求數據,不太安全
2、由于瀏覽器和服務器對URL長度有限制,因此在URL后面附帶的參數是有限制的,通常不能超過1KB
- (IBAction)login {
NSString loginUser = self.userName.text;
NSString loginPwd = self.pwd.text;
if (loginUser.length==0) {
[MBProgressHUD showError:@"請輸入用戶名!"];
return;
}
if (loginPwd.length==0) {
[MBProgressHUD showError:@"請輸入密碼!"];
return;
}
// 增加蒙板
[MBProgressHUD showMessage:@"正在登錄中....."];
//默認是get方式請求:get方式參數直接拼接到url中
NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/myService/login?username=%@&pwd=%@",loginUser,loginPwd];
//post方式請求,參數放在請求體中
//NSString *urlStr = @"http://localhost:8080/myService/login";
//URL轉碼
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//設置超時時間(默認60s)
request.timeoutInterval = 15;
//設置請求方式
request.HTTPMethod = @"POST";
//設置請求體
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", loginUser,loginPwd];
// NSString --> NSData
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
// 設置請求頭信息
[request setValue:@"iphone" forHTTPHeaderField:@"User-Agent"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//隱藏蒙板
[MBProgressHUD hideHUD];
if(connectionError || data==nil){
[MBProgressHUD showError:@"網絡繁忙!稍后再試!"];
return ;
}else{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}else{
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}
}];
}</pre>
POST
特點:
1、把所有請求參數放在請求體(HTTPBody)中
2、理論上講,發給服務器的數據的大小是沒有限制
3、請求數據相對安全(沒有絕對的安全)
// 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/myService/order"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.timeoutInterval = 15;
request.HTTPMethod = @"POST";
NSDictionary *orderInfo = @{
@"shop_id" : @"1111",
@"shop_name" : @"的地方地方",
@"user_id" : @"8919"
};
NSData *json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = json;
// 5.設置請求頭:這次請求體的數據不再是普通的參數,而是一個JSON數據
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(connectionError || data==nil){
[MBProgressHUD showError:@"網絡繁忙!稍后再試!"];
return ;
}else{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}else{
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}
}];</pre>
url轉碼問題(URL中不能包含中文)
1、這方法已過時
NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login?username=喝喝&pwd=123"];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
2、官方推薦使用:
NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login?username=喝喝&pwd=123"];
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];