ios開發網路篇 Get請求和Post請求

2021-07-12 06:26:45 字數 2207 閱讀 1862

一.get請求和post請求簡單說明

建立get請求

//1.設定請求路徑

nsstring *urlstr = [nsstring stringwithformat:@"",self

.username

.text,self

.pwd

.text];

nsurl *url = [nsurl urlwithstring:urlstr];

//2.建立請求物件

nsurlrequest *request = [nsurlrequest requestwithurl:url];

建立post請求

//1.設定請求路徑

nsurl *url = [nsurl urlwithstring:@""];

//2.建立請求物件

nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url]; //預設為get請求

request.timeoutinterval=5.0; //設定請求超時5秒

request.httpmethod=@"post"; //設定請求方法

//設定請求體

nsstring *param = [nsstring stringwithformat:@"username=%@&pwd=%@",self

.username

.text,self

.pwd

.text];

//把拼接後的字串轉換為data,設定請求體

request.httpbody = [param datausingencoding:nsutf8stringencoding];

二.比較

建議:提交使用者的隱私資料一定要使用post請求

相對post請求而言,get請求的所有引數都直接暴露在url中,請求的url一般會記錄在伺服器的訪問日誌中,而伺服器的訪問日誌是黑客攻擊的重點物件之一

使用者的隱私資料如登入密碼,銀行帳號等

三.使用

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

//1.設定請求路徑

nsurl *url=[nsurl urlwithstring:@""];//不需要傳遞引數

//2.建立請求物件

nsmutableurlrequest *request=[nsmutableurlrequest requestwithurl:url];//預設為get請求

request.timeoutinterval=5.0;//設定請求超時為5秒

request.httpmethod=@"post";//設定請求方法

//設定請求體

nsstring *param=[nsstring stringwithformat:@"username=%@&pwd=%@",self

.username

.text,self

.pwd

.text];

//把拼接後的字串轉換為data,設定請求體

//客戶端型別,只能寫英文

[request setvalue:@"ios+android" forhttpheaderfield:@"user-agent"];

2.加強對中文的處理

//1.設定請求路徑

nsstring *urlstr=[nsstring stringwithformat:@"",self

.username

.text,self

.pwd

.text];

//轉碼

urlstr= [urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

nsurl *url=[nsurl urlwithstring:urlstr];

//2.建立請求物件

nsurlrequest *request=[nsurlrequest requestwithurl:url];

iOS開發網路篇 GET請求和POST請求

一 get請求和post請求簡單說明 建立get請求 1 1.設定請求路徑 2 nsstring urlstr nsstring stringwithformat self.username.text,self.pwd.text 3 nsurl url nsurl urlwithstring url...

iOS開發網路篇 GET請求和POST請求

一 get請求和post請求簡單說明 建立get請求 1 1.設定請求路徑 2 nsstring urlstr nsstring stringwithformat self.username.text,self.pwd.text 3 nsurl url nsurl urlwithstring url...

iOS開發網路篇 GET請求和POST請求

一 get請求和post請求簡單說明 建立get請求 1 1.設定請求路徑 2 nsstring urlstr nsstring stringwithformat self.username.text,self.pwd.text 3 nsurl url nsurl urlwithstring url...