IOS网络学习-5、GET请求和POST请求

本文详细对比了HTTP请求中的GET与POST方法的区别,包括安全性、参数处理等方面,并提供了iOS平台的具体实现示例。

get与post的区别。

以下内容转载自http://www.cnblogs.com/wendingding/p/3813706.html

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

创建GET请求

<span style="background-color: rgb(255, 255, 255);">//    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.发送请求</span>

服务器:

创建POST请求

<span style="background-color: rgb(255, 255, 255);">// 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.发送请求</span>

服务器:

二、比较

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

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

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

 

三、使用

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

<span style="background-color: rgb(255, 255, 255);">// 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"];</span>

服务器:

2.加强对中文的处理

问题:URL不允许写中文

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

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

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

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

解决:进行转码

<span style="background-color: rgb(255, 255, 255);">//    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];</span>

调试查看:

服务器:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值