【iOS进阶】【Web基础】3-GET&POST、简单的网络编程实现
一、在/User/用户名/Sites文件夹添加两个文件
1>html文件:login.html
<html> <head> <meta charset="UTF-8"> <title>GET和POST请求测试</title> </head> <body> <b>get请求</b><br/> <h1> <form action="login.php" method="get"> 用户名:<input type="text" name="username" value="" /><br/> 密码:<input type="password" name="password" value="" /><br/> <input type="submit" value="请求"/> <input type="reset" value="重置"/> </form> </h1> <b>post请求</b><br/> <h1> <form action="login.php" method="post"> 用户名:<input type="text" name="username" value="" /><br/> 密码:<input type="password" name="password" value="" /><br/> <input type="submit" value="请求"/> <input type="reset" value="重置"/> </form> </h1> </body> </html>
2>php文件:login.php
<?php class itcastUsers{ private $db; //构造函数- 建立数据库连接 function __construct(){ //连接mysql数据库到字符串 $this->db = new mysqli('127.0.0.1','root','123456','itcast'); if (mysqli_connect_errno()){ printf("连接错误:%s\n",mysqli_connect_errno()); exit(); } $this->db->autocommit(FALSE); } //析构函数 - 关闭数据库连接 function __destruct(){ //关闭数据库 $this->db->close(); } //用户登录 function userLogin(){ if (isset($_GET['username']) && isset($_GET['password'])){ //获取GET请求参数 $accessType = '[GET]'; //提示:请求参数的设置应谨慎 $name = $_GET['username']; $password = $_GET['password']; } else if (isset($_POST['username']) && isset($_POST['password'])){ //获取POST请求参数 $accessType = '[POST]'; $name = $_GET['username']; $password = $_GET['password']; } else { echo('非法请求'); return false; } //设置数据库查询字符编码 $this->db->query('set names utf8'); //查询请求-sql语句 $data = $this -> db -> query("select id,username from userInfo where username='$name' and userpwd = '$password'"); //绑定查询参数 $this->db->real_escape_string($name); $this->db->real_escape_string($password); //提交查询请求 $this->db->commit(); //提交一条查询结果 $row = $data->fetch_assoc(); //将查询结果绑定到数据字典 $result = [ //提示:这里应该用小写 'userId' => $row['id'], 'userName' => $row['username'] ]; //将数据字典使用JSON编码 echo json_encode($result); return true; } } header('Content-Type:text/html;charset=utf-8'); $itcast = new itcastUsers; $itcast -> userLogin(); ?>
3>打开浏览器输入网址:www.sites.com,点击login.html进入,如下图
二、GET & POST
1>GET请求:
2>GET请求示例:
3>POST请求:
要通过Firebug才能查看Post请求的内容
4>POST请求示例:
5>在浏览器中判断GET&POST请求
6>GET & POST
三、iOS网络发送网络请求
0>UI的设计
1>iOS网络发送网络请求的步骤
1.实例化URL(网络资源)
2.根据URL建立URLRequest(网络请求)
默认为GET请求
对于POST请求,需要创建请求的数据体
3.利用URLConnection发送网络请求(建立连接)
4.获得结果
2>NSURLConnection提供了两个静态方法可以直接以同步或异步的方式向服务器发送网络请求
1.同步请求:
sendSynchronousRequest:returningResponse:error:
2.异步请求:
sendAsynchronousRequest:queue: completionHandler:
#import "ViewController.h" @interface ViewController () /** * 用户名文本框 */ @property (weak, nonatomic) IBOutlet UITextField *idView; /** * 密码文本框 */ @property (weak, nonatomic) IBOutlet UITextField *pwdView; /** * 登陆按钮 */ - (IBAction)userLogonBtn:(id)sender; /** * 提示登录是否成功的标签 */ @property (weak, nonatomic) IBOutlet UILabel *promptLabel; /** * 显示返回内容的标签 */ @property (weak, nonatomic) IBOutlet UILabel *returnLabel; @end @implementation ViewController /** 所有网络请求,统一使用异步请求! 在今后的开发中,如果使用简单的get/head请求,可以使用NSURLConnction异步方法 GET查/POST增/PUT改/DELETE删/HEAD GET 1> URL 2> NSURLRequest 3> NSURLConnction 异步 POST 1> URL 2> NSMutableURLRequest .HTTPMethod = @"POST"; .HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding]; 3> NSURLConnction 异步 */ - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)userLogonBtn:(id)sender { [self postLogin]; } #pragma mark - POST登录 -(void)postLogin{ //1. URL NSURL *url = [NSURL URLWithString:@"http://www.sites.com/login.php"]; //2.可变请求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //2.1 默认为GET请求 request.HTTPMethod = @"POST"; //2.2 数据体 NSString *str = [NSString stringWithFormat:@"username=%@&password=%@",self.idView.text,self.pwdView.text]; //2.2 将字符串转换成数据 request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding]; //3.连接,异步 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if(connectionError != nil) return; //网络请求结束之后执行 //将Data转换成字符串 NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //更新UI应放在主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.promptLabel.text=@"登录成功!!"; self.returnLabel.text=[NSString stringWithFormat:@"返回:%@",str]; }]; NSLog(@"%@",str); }]; } #pragma mark - GET登录 -(void)getLogon{ //1. URL NSString *urlStr = [NSString stringWithFormat:@"http://www.sites.com/login.php?username=%@&password=%@", self.idView.text, self.pwdView.text]; NSURL *url = [NSURL URLWithString:urlStr]; //2. Request NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.Connection #warning 所有网络请求,统一使用异步请求! /** * 1> 登录完成之前,不能做后续工作 * 2> 登录进行中,可以循序用户干点别的会更好 * 3> 让登录操作在其他线程中进行,就不会阻塞主线程的工作 * 4> 结论:登录也是异步访问,中间需要阻塞住 */ [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if(connectionError != nil) return; //网络请求结束之后执行 //将Data转换成字符串 NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; //更新UI应放在主线程 [[NSOperationQueue mainQueue] addOperationWithBlock:^{ self.promptLabel.text=@"登录成功!"; self.returnLabel.text=[NSString stringWithFormat:@"返回:%@",str]; }]; NSLog(@"%@",str); }]; //NSURLResponse *response =nil; // 1.&response是指针的地址 // 2.error:是NULL,而不是nil // NULL是C语言的,等于0。在C语言中,如果将指针的地址指向0就不会有危险 // nil是OC的,它是一个空对象 //同步请求 //[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL]; } @end
3>通过实现NSURLConnectionDataDelegate代理方法
#import "DYWebDelegateViewController.h" @interface DYWebDelegateViewController() <NSURLConnectionDataDelegate> /** * 保存从服务器接受到的数据,进行拼接工作 */ @property (nonatomic,strong) NSMutableData *data; @property (weak, nonatomic) IBOutlet UITextField *idView; @property (weak, nonatomic) IBOutlet UITextField *pwdView; - (IBAction)userLogonBtn:(id)sender; @property (weak, nonatomic) IBOutlet UILabel *promptLabel; @property (weak, nonatomic) IBOutlet UILabel *returnLabel; @end @implementation DYWebDelegateViewController - (void)viewDidLoad { [super viewDidLoad]; } - (IBAction)userLogonBtn:(id)sender { [self getLogin]; } -(void)getLogin{ //1. URL NSString *urlStr = [NSString stringWithFormat:@"http://www.sites.com/login.php?username=%@&password=%@", self.idView.text, self.pwdView.text]; NSURL *url = [NSURL URLWithString:urlStr]; //2. Request NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.Connection NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self]; // 开始工作,在很多多线程技术中。开始一般是:start run [conn start]; } #pragma mark - NSURLConnectionDataDelegate代理方法 /** * 接收到响应 */ -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ // 准备工作 // 按钮点击就会有网络请求,应避免重复开辟空间 if(!self.data){ self.data = [NSMutableData data]; } else{ [self.data setData:nil]; } } /** * 接受到数据,如果数据量大,例如视频,会被调用多次 */ -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ //拼接数据 [self.data appendData:data]; } /** * 接受完成,做最终的处理工作 */ -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ //最终处理 NSString *str = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]; NSLog(@"%@ - %@",[NSThread currentThread],str); } /** * 出错处理,网络的出错的可能性非常高 */ -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"%@",error.localizedDescription); } @end

浙公网安备 33010602011771号