ios开发网络请求---get请求post请求

get请求post请求的简单介绍

创建get请求,代码如下:

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()<UITextFieldDelegate>
 4 @property(strong,nonatomic) UITextField *textinfo;
 5 @end
 6 
 7 @implementation ViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     self.textinfo=[[UITextField alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
12     self.textinfo.borderStyle=1;
13     [self.textinfo addTarget:self action:@selector(change) forControlEvents:UIControlEventEditingChanged];
14     [self.view addSubview:self.textinfo];
15 -(void)change
16 {
17     //设置请求路径
18     NSString *path=[NSString stringWithFormat:@"http://1.studyios.sinaapp.com/gyxy.php?a=%@&b=%@&c=%@",self.textinfo.text,self.textinfo.text,self.textinfo.text];
19     //封装URL 即 网址
20     NSURL *url=[[NSURL alloc] initWithString:path];
21     //    NSData *data=[NSData dataWithContentsOfURL:url];
22     //创建会话对象
23     NSURLSession *session=[NSURLSession sharedSession];
24     //创建请求命令
25     NSURLRequest *request=[NSURLRequest requestWithURL:url];
26     //执行会话任务
27     NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
28         //json解析
29         NSArray *array=[NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableLeaves  error:nil];
30         NSLog(@"%@",array);
31     }];
32     //执行真正的任务
33     [ task resume];
34 
35 }

创建post请求:

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()
 4 
 5 @end
 6 
 7 @implementation ViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     //请求路径
12     NSString *path=@"http://1.studyios.sinaapp.com/mypost.php";//不需要传参数
13     //封装URL 即 网址
14     NSURL *url=[NSURL URLWithString:path];
15     //创建请求对象request
16     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];//默认为get请求
17     //设置请求超时为5秒
18     request.timeoutInterval=5.0;
19     //post请求
20     request.HTTPMethod=@"POST";
21     //参数
22     NSString *param=[NSString stringWithFormat:@"can1=text1&can2=text2"];
23     //将参数转化成data
24     NSData *data=[param dataUsingEncoding:NSUTF8StringEncoding];
25     //request的参数的主体
26     request.HTTPBody=data;
27     NSURLSession *session=[NSURLSession sharedSession];
28     NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
29         NSArray *arr=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
30         NSLog(@"%@",arr);
31     }];
32     [task resume];
33 }

比较

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

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

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

原文地址:https://www.cnblogs.com/zhaochaobin/p/5330960.html