iOS網路編程開發GET請求和POST請求

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   ar   color   os   使用   

iOS網路編程開發GET請求和POST請求

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

建立GET請求

//    1.佈建要求路徑    NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];    NSURL *url=[NSURL URLWithString:urlStr];    //    2.建立請求對象    NSURLRequest *request=[NSURLRequest requestWithURL:url];    //    3.發送請求

 

伺服器:

建立POST請求

// 1.佈建要求路徑    NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要傳遞參數    //    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];    //    3.發送請求

 

伺服器:

二、比較

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

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

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

 

三、使用

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

// 1.佈建要求路徑    NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要傳遞參數    //    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];        //用戶端類型,只能寫英文    [request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];

 

伺服器:

2.加強對中文的處理

問題:URL不允許寫中文

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

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

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

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

解決:進行轉碼

//    1.佈建要求路徑    NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];   //轉碼   urlStr= [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSURL *url=[NSURL URLWithString:urlStr];    //    2.建立請求對象    NSURLRequest *request=[NSURLRequest requestWithURL:url];

 

調試查看:

伺服器:

 

  

iOS網路編程開發GET請求和POST請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.