• IOS-网络(GET请求和POST请求、HTTP通信过程、请求超时、URL转码)


      1 //
      2 //  ViewController.m
      3 //  IOS_0129_HTTP请求
      4 //
      5 //  Created by ma c on 16/1/29.
      6 //  Copyright © 2016年 博文科技. All rights reserved.
      7 //
      8 
      9 #import "ViewController.h"
     10 #import "MBProgressHUD+MJ.h"
     11 
     12 @interface ViewController ()
     13 @property (weak, nonatomic) IBOutlet UITextField *textName;
     14 @property (weak, nonatomic) IBOutlet UITextField *textPassword;
     15 
     16 - (IBAction)btnlogin;
     17 
     18 @end
     19 
     20 @implementation ViewController
     21 
     22 /*
     23  
     24  1.发送HTTP请求的方法
     25  1>在HTTP/1.1协议中,定义了8种发送HTTP请求的方法
     26    GET,POST,OPTIONS,HEAD,PUT,DELETE,TRACE,CONNECT,PATCH
     27  2>根据HTTP协议设计初衷,不同的方法对资源有不同的操作方式
     28    PUT:增
     29    DELETE:删
     30    POST:改
     31    GET:查
     32  3>最常用的是GET,POST(实际上GET,POST都能办到增删改查)
     33  4>参数 - 传递给服务器的具体数据
     34  
     35  2.GET和POST对比
     36  1>GET和POST主要体现在数据传递上
     37    a.GET在请求URL后面以?的形式加上发送给服务器的参数,多个参数之间用&隔开
     38    b.URL后面跟的参数不能超过1KB
     39  
     40    c.POST发送给服务器的参数全部放在请求体中
     41    d.理论上,POST传递的数据量没有限制(看服务器处理能力)
     42  
     43  3.GET和POST选择
     44  1>传递大量数据只能用POST(文件上传)
     45  2>GET安全性比POST差,机密信息用POST
     46  3>仅仅是索取数据(数据查询)用GET
     47  4>如果是增删改查数据,建议用POST
     48  
     49  4.HTTP通信过程 - 请求
     50  1>HTTP协议规定:1个完整的由客户端发送给服务器的HTTP请求包含以下内容
     51  a.请求行:包含了请求方法、请求资源路径、HTTP版本协议
     52  b.请求头:包含了对客户端的环境描述、客户端请求的主机地址等
     53    Host:客户端想访问的服务器主机地址
     54    User-Agent:客户端类型,客户端的软件环境
     55    Accept:客户端所能接收的数据类型
     56    Accept-Language:客户端的语言环境
     57    Accept-Encoding:客户端所支持的数据压缩格式
     58   c.请求体:客户端发送给服务器的具体数据
     59  
     60  5.HTTP通信过程 - 响应
     61  1>客户端向服务器发送请求,服务器应当作出响应,即返回数据给客户端
     62  2>HTTP协议规定:1个完整的HTTP响应中应该包含以下内容
     63  a.状态行:包含了HTTP协议版本、状态码、状态英文名称
     64  b.响应头:包含了对服务器的描述、对返回数据的描述
     65    Server:服务器的类型
     66    Content-Type:返回的数据类型
     67    Content-Length:返回的数据长度
     68    Date:响应的时间
     69  3>实体内容:服务器返回给客户端的具体数据
     70  4>常见响应状态码:
     71  */
     72 
     73 - (void)viewDidLoad {
     74     [super viewDidLoad];
     75     
     76     self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
     77 }
     78 
     79 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
     80 {
     81     [self.view endEditing:YES];
     82 }
     83 
     84 - (IBAction)btnlogin {
     85     
     86     NSString *usernameText = self.textName.text;
     87     if (usernameText.length == 0) {
     88         [MBProgressHUD showError:@"请输入账号"];
     89         return;
     90     }
     91     self.textPassword.secureTextEntry = YES;
     92     NSString *password = self.textPassword.text;
     93     if (password.length == 0) {
     94         [MBProgressHUD showError:@"请输入密码"];
     95         return;
     96     }
     97     //1.GET请求默认
     98 //    //创建一个NSURL:请求路径
     99 //    NSString *strURL = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText,password];
    100     
    101 //    //NSURL后面不能包含中文,得对中文进行转码
    102 //    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    103     
    104 //    NSURL *url = [NSURL URLWithString:strURL];
    105 //    //创建一个请求
    106 //    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    107     
    108     // 增加蒙板
    109     [MBProgressHUD showMessage:@"正在拼命加载..."];
    110     
    111     //2.POST请求
    112     NSString *strURL = @"http://localhost:8080/MJServer/login";
    113     NSURL *url = [NSURL URLWithString:strURL];
    114     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    115     
    116     //5s后请求超时(默认60s超时)
    117     request.timeoutInterval = 5;
    118     //设置请求方式
    119     request.HTTPMethod = @"POST";
    120     //设置请求头
    121     [request setValue:@"iPhone6" forHTTPHeaderField:@"User-Agent"];
    122     
    123     //设置请求体
    124     NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@",usernameText,password];
    125     //NSString -> NSData
    126     request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    127     
    128     //异步请求
    129     [self sendAsyncWithRequest:request];
    130     
    131 }
    132 //异步请求
    133 - (void)sendAsyncWithRequest:(NSURLRequest *)request
    134 {
    135     NSOperationQueue *queue = [NSOperationQueue mainQueue];
    136     
    137     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    138         
    139         //隐藏蒙版
    140         [MBProgressHUD hideHUD];
    141         NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
    142         NSString *msg = [NSHTTPURLResponse localizedStringForStatusCode:resp.statusCode];
    143         NSLog(@"%ld %@ %@",resp.statusCode, msg, resp.allHeaderFields);
    144         
    145         //这个block会在请求完毕的时候自动调用
    146         if (connectionError || data == nil) {
    147             [MBProgressHUD showError:@"请求失败"];
    148             return;
    149         }
    150         //解析服务器返回的JSON数据
    151         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    152         NSString *error = dict[@"error"];
    153         if (error) {
    154             [MBProgressHUD showError:error];
    155         }
    156         else{
    157             NSString *success = dict[@"success"];
    158             [MBProgressHUD showSuccess:success];
    159         }
    160     }];
    161 }
    162 
    163 @end
  • 相关阅读:
    Transfer-Encoding: chunked
    使用Kubeadm搭建Kubernetes集群
    连载二:Oracle迁移文章大全
    今晚直播:WLS/WAS故障基本分析介绍
    判断用户是否登录
    row_number() over (partition by a.sql_id order by a.id desc ) r
    Django admin添加用户
    从数据仓库到百万标签库,精细化数据管理,这么做就够了
    用 C 语言开发一门编程语言 — 更好的语言
    ubuntu下 全然卸载火狐浏览器
  • 原文地址:https://www.cnblogs.com/oc-bowen/p/5172072.html
Copyright © 2020-2023  润新知