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

最新博文发布地址 花田半亩http://wendingding.com/

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

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

创建GET请求

1 //    1.设置请求路径
2     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
3     NSURL *url=[NSURL URLWithString:urlStr];
4     
5 //    2.创建请求对象
6     NSURLRequest *request=[NSURLRequest requestWithURL:url];
7     
8 //    3.发送请求

服务器:

创建POST请求

复制代码
 1     // 1.设置请求路径
 2     NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要传递参数
 3     
 4 //    2.创建请求对象
 5     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
 6     request.timeoutInterval=5.0;//设置请求超时为5秒
 7     request.HTTPMethod=@"POST";//设置请求方法
 8     
 9     //设置请求体
10     NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
11     //把拼接后的字符串转换为data,设置请求体
12     request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
13     
14 //    3.发送请求
复制代码

服务器:

二、比较

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

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

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

 

三、使用

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

复制代码
 1     // 1.设置请求路径
 2     NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要传递参数
 3     
 4 //    2.创建请求对象
 5     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
 6     request.timeoutInterval=5.0;//设置请求超时为5秒
 7     request.HTTPMethod=@"POST";//设置请求方法
 8     
 9     //设置请求体
10     NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
11     //把拼接后的字符串转换为data,设置请求体
12     request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
13     
14     //客户端类型,只能写英文
15     [request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];
复制代码

服务器:

2.加强对中文的处理

问题:URL不允许写中文

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

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

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

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

解决:进行转码

1 //    1.设置请求路径
2     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
3    //转码
4    urlStr= [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5     NSURL *url=[NSURL URLWithString:urlStr];
6     
7 //    2.创建请求对象
8     NSURLRequest *request=[NSURLRequest requestWithURL:url];

调试查看:

服务器:

 说明:使用NSURLSession发送GET和POST请求请参考最新博文:http://www.cnblogs.com/wendingding/p/5168772.html

posted on   文顶顶  阅读(135154)  评论(9编辑  收藏  举报

编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· DeepSeek “源神”启动!「GitHub 热点速览」
· 上周热点回顾(2.17-2.23)
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示