iOS開發網路篇—GET請求和POST請求,iosget請求post
iOS開發網路篇—GET請求和POST請求
一、GET請求和POST請求簡單說明
建立GET請求
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.發送請求
伺服器:
建立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.發送請求
伺服器:
二、比較
建議:提交使用者的隱私資料一定要使用POST請求
相對POST請求而言,GET請求的所有參數都直接暴露在URL中,請求的URL一般會記錄在伺服器的訪問日誌中,而伺服器的訪問日誌是駭客攻擊的重點對象之一
使用者的隱私資料如登入密碼,銀行帳號等。
三、使用
1.通過要求標頭告訴伺服器,用戶端的類型(可以通過修改,欺騙伺服器)
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"];
伺服器:
2.加強對中文的處理
問題:URL不允許寫中文
在GET請求中,相關程式碼片段打斷點以驗證。
在字串的拼接參數中,使用者名稱使用“文頂頂”.
轉換成URL之後整個變成了空值。
提示:URL裡面不能包含中文。
解決:進行轉碼
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];
調試查看:
伺服器: