IOS开发--网络篇-->GET请求和POST请求

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

iOS开发网络篇—GET请求和POST请求

一、GET请求和POST请求简单说明

创建GET请求

1// 1.设置请求路径2NSString*urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];

3NSURL*url=[NSURL URLWithString:urlStr];

4

5// 2.创建请求对象6NSURLRequest*request=[NSURLRequest requestWithURL:url];

7

8 //3.发送请求

服务器:

创建POST请求

1// 1.设置请求路径2NSURL*URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要传递参数3

4// 2.创建请求对象5NSMutableURLRequest*request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求6 request.timeoutInterval=5.0;//设置请求超时为5秒7 request.HTTPMethod=@"POST";//设置请求方法8

9//设置请求体10NSString*param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];

11//把拼接后的字符串转换为data,设置请求体12 request.HTTPBody=[paramdataUsingEncoding:NSUTF8StringEncoding];

13

14//3.发送请求

服务器:

二、比较

建议:提交用户的隐私数据一定要使用POST请求

相对POST请求而言,GET请求的所有参数都直接暴露在URL中,请求的URL一般会记录在服务器的访问日志中,而服务器的访问日志是黑客攻击的重点对象之一

用户的隐私数据如登录密码,银行账号等。

三、使用

1.通过请求头告诉服务器,客户端的类型(可以通过修改,欺骗服务器)

1// 1.设置请求路径2NSURL*URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要传递参数3

4// 2.创建请求对象5NSMutableURLRequest*request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求6 request.timeoutInterval=5.0;//设置请求超时为5秒7 request.HTTPMethod=@"POST";//设置请求方法8

9//设置请求体10NSString*param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];

11//把拼接后的字符串转换为data,设置请求体12 request.HTTPBody=[paramdataUsingEncoding:NSUTF8StringEncoding];

13

14//客户端类型,只能写英文15 [requestsetValue:@"ios+android"forHTTPHeaderField:@"User-Agent"];

服务器:

2.加强对中文的处理

问题:URL不允许写中文

在GET请求中,相关代码段打断点以验证。

在字符串的拼接参数中,用户名使用“文顶顶”.

转换成URL之后整个变成了空值。

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

解决:进行转码

1// 1.设置请求路径2NSString*urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];

3//转码4 urlStr= [urlStrstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

5NSURL*url=[NSURL URLWithString:urlStr];

6

7// 2.创建请求对象8NSURLRequest*request=[NSURLRequest requestWithURL:url];

调试查看:

服务器:

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航