一、GET請求和POST請求簡單說明
創(chuàng)建GET請求
設置請求路徑
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];
.創(chuàng)建請求對象NSURLRequest *request=[NSURLRequest requestWithURL:url];
.發(fā)送請求
服務器:
創(chuàng)建POST請求
1//1.設置請求路徑2NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];
//不需要傳遞參數
//創(chuàng)建請求對象
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];
.發(fā)送請求
服務器:
二、比較
建議:提交用戶的隱私數據一定要使用POST請求
相對POST請求而言,GET請求的所有參數都直接暴露在URL中是嗜,請求的URL一般會記錄在服務器的訪問日志中,而服務器的訪問日志是黑客攻擊的重點對象之一
用戶的隱私數據如登錄密碼,銀行賬號等媳危。
三、使用
1.通過請求頭告訴服務器冈敛,客戶端的類型(可以通過修改待笑,欺騙服務器)
1//1.設置請求路徑
NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];
//不需要傳遞參數
創(chuàng)建請求對象
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];
//默認為get請求6request.timeoutInterval=5.0;
//設置請求超時為5秒
request.HTTPMethod=@"POST";
//設置請求方法89
//設置請求體10NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
//把拼接后的字符串轉換為data,設置請求體
request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
客戶端類型抓谴,只能寫英文15[request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];
服務器:
2.加強對中文的處理
問題:URL不允許寫中文
在GET請求中暮蹂,相關代碼段打斷點以驗證。
在字符串的拼接參數中癌压,用戶名使用“文頂頂”.
轉換成URL之后整個變成了空值仰泻。
提示:URL里面不能包含中文。
解決:進行轉碼
1設置請求路徑2NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
//轉碼4urlStr= [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlStr];
2創(chuàng)建請求對象8NSURLRequest *request=[NSURLRequest requestWithURL:url];
調試查看:
服務器: