天天看點

iOS開發網絡—04GET請求和POST請求

iOS開發網絡篇—GET請求和POST請求

一、GET請求和POST請求簡單說明

建立GET請求

iOS開發網絡—04GET請求和POST請求
1 //    1.設定請求路徑
2     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
3     NSURL *url=[NSURL URLWithString:urlStr];
4     
5 //    2.建立請求對象
6     NSURLRequest *request=[NSURLRequest requestWithURL:url];
7     
8 //    3.發送請求      
iOS開發網絡—04GET請求和POST請求

伺服器:

iOS開發網絡—04GET請求和POST請求

建立POST請求

iOS開發網絡—04GET請求和POST請求
1     // 1.設定請求路徑
 2     NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要傳遞參數
 3     
 4 //    2.建立請求對象
 5     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//預設為get請求
 6     request.timeoutInterval=5.0;//設定請求逾時為5秒
 7     request.HTTPMethod=@"POST";//設定請求方法
 8     
 9     //設定請求體
10     NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
11     //把拼接後的字元串轉換為data,設定請求體
12     request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
13     
14 //    3.發送請求      
iOS開發網絡—04GET請求和POST請求

伺服器:

iOS開發網絡—04GET請求和POST請求

二、比較

建議:送出使用者的隐私資料一定要使用POST請求

相對POST請求而言,GET請求的所有參數都直接暴露在URL中,請求的URL一般會記錄在伺服器的通路日志中,而伺服器的通路日志是黑客攻擊的重點對象之一

使用者的隐私資料如登入密碼,銀行賬号等。

三、使用

1.通過請求頭告訴伺服器,用戶端的類型(可以通過修改,欺騙伺服器)

iOS開發網絡—04GET請求和POST請求
1     // 1.設定請求路徑
 2     NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要傳遞參數
 3     
 4 //    2.建立請求對象
 5     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//預設為get請求
 6     request.timeoutInterval=5.0;//設定請求逾時為5秒
 7     request.HTTPMethod=@"POST";//設定請求方法
 8     
 9     //設定請求體
10     NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
11     //把拼接後的字元串轉換為data,設定請求體
12     request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
13     
14     //用戶端類型,隻能寫英文
15     [request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];      
iOS開發網絡—04GET請求和POST請求

伺服器:

iOS開發網絡—04GET請求和POST請求

2.加強對中文的處理

問題:URL不允許寫中文

在GET請求中,相關代碼段打斷點以驗證。

在字元串的拼接參數中,使用者名使用“文頂頂”.

iOS開發網絡—04GET請求和POST請求

轉換成URL之後整個變成了空值。

iOS開發網絡—04GET請求和POST請求

提示:URL裡面不能包含中文。

解決:進行轉碼

iOS開發網絡—04GET請求和POST請求
1 //    1.設定請求路徑
2     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
3    //轉碼
4    urlStr= [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5     NSURL *url=[NSURL URLWithString:urlStr];
6     
7 //    2.建立請求對象
8     NSURLRequest *request=[NSURLRequest requestWithURL:url];      
iOS開發網絡—04GET請求和POST請求

調試檢視:

iOS開發網絡—04GET請求和POST請求

伺服器:

iOS開發網絡—04GET請求和POST請求

繼續閱讀