zoukankan      html  css  js  c++  java
  • IOS-网络(HTTP请求、同步请求、异步请求、JSON解析数据)

      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  1.常见的发送HTTP请求的方案:
     23  1>苹果原生自带的
     24    NSURLConnection:用法简单,最经典,最直接
     25    NSURLSession:功能比NSURLConnection强大
     26    CFNetwork:NSURL底层,纯C语言
     27  2>第三方框架
     28    ASIHttpRequest:“HTTP终结者”,功能及其强大,可惜停止更新
     29    AFNetWorking:简单易用,提供基本够用的常用功能,维护者多
     30    MKNetWorkKit:简单易用,维护者使用者少
     31  3>建议
     32    为了提高开发效率,企业开发用的基本是第三方框架
     33  
     34  2.常用类
     35  1>NSURL:请求地址
     36  2>NSURLRequest:一个NSURLRequest对象代表一个请求 - 包含信息有:
     37    a.一个NSURL对象
     38    b.请求方法、请求头、请求体
     39    c.请求超时
     40  3>NSMutableURLRequest:
     41  4>NSURLConnection - 负责发送请求,建立客户端与服务器的连接
     42    发送NSURLRequest的数据给服务器,并收来自服务器响应的数据
     43  
     44  3.NSURLConnection使用步骤:
     45    1>创建NSURL对象,并设置请求路径
     46    2>传入一个NSURL对象创建NSURLRequest对象,设置请求头和请求体
     47    3>使用NSURLConnection发送NSURLRequest
     48  */
     49 
     50 - (void)viewDidLoad {
     51     [super viewDidLoad];
     52     
     53     self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
     54 }
     55 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
     56 {
     57     [self.view endEditing:YES];
     58 }
     59 
     60 
     61 - (IBAction)btnlogin {
     62     
     63     NSString *usernameText = self.textName.text;
     64     if (usernameText.length == 0) {
     65         [MBProgressHUD showError:@"请输入账号"];
     66         return;
     67     }
     68     self.textPassword.secureTextEntry = YES;
     69     NSString *password = self.textPassword.text;
     70     if (password.length == 0) {
     71         [MBProgressHUD showError:@"请输入密码"];
     72         return;
     73     }
     74     NSLog(@"发送数据给服务器");
     75     
     76     /*
     77      接口文档:定义描述服务器端的请求接口
     78      1>请求路径URL:客户端应该请求哪个路径
     79      2>请求参数:客户端要发给服务器的数据
     80      3>请求结果:服务器要返回什么给客户端
     81      */
     82     
     83     //创建一个NSURL:请求路径
     84     NSString *strURL = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText,password];
     85     NSURL *url = [NSURL URLWithString:strURL];
     86     //创建一个请求
     87     NSURLRequest *request = [NSURLRequest requestWithURL:url];
     88 
     89     //同步请求
     90     [self sendSyncWithRequest:request];
     91     //异步请求
     92     [self sendAsyncWithRequest:request];
     93     
     94 }
     95 //异步请求
     96 - (void)sendAsyncWithRequest:(NSURLRequest *)request
     97 {
     98     NSOperationQueue *queue = [NSOperationQueue mainQueue];
     99     
    100     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
    101         //这个block会在请求完毕的时候自动调用
    102         if (connectionError || data == nil) {
    103             [MBProgressHUD showError:@"请求失败"];
    104             return;
    105         }
    106         //解析服务器返回的JSON数据
    107         NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    108         NSString *error = dict[@"error"];
    109         if (error) {
    110             [MBProgressHUD showError:error];
    111         }
    112         else{
    113             NSString *success = dict[@"success"];
    114             [MBProgressHUD showSuccess:success];
    115         }
    116     }];
    117 }
    118 
    119 //同步请求
    120 - (void)sendSyncWithRequest:(NSURLRequest *)request
    121 {
    122     //发送用户名和密码给服务器(HTTP协议)
    123     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    124     /*
    125      JSON
    126      1>JSON是一种轻量级的数据格式,一般用于数据交互
    127      服务器返回给客户端的数据一般都是JSON格式或者XML格式
    128      标准的JSON合适注意点:key必须用双引号
    129      
    130      2>要想从JSON中挖出具体数据得对JSON进行解析
    131      JSON           OC
    132      {}-----------NSDictonary
    133      []-----------NSArray
    134      " "-----------NSString
    135      数字-----------NSNumber
    136      
    137      3>JSON解析方案
    138      第三方框架:JSONKit、SBJson、TouchJSON(性能从左到右,越差)
    139      苹果原生(自带):NSJSONSerialization(性能最好)
    140      4>JSON数据转-->OC对象
    141      + (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
    142      5>OC对象-->JSON数据
    143      + (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
    144      */
    145     //解析服务器返回的JSON数据
    146     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    147     NSString *error = dict[@"error"];
    148     if (error) {
    149         [MBProgressHUD showError:error];
    150     }
    151     else{
    152         NSString *success = dict[@"success"];
    153         [MBProgressHUD showSuccess:success];
    154     }
    155     
    156 }
    157 @end
  • 相关阅读:
    通讯录封装实现
    简单通讯录的实现 main..h .m文件全部
    iOS 开发 OC编程 字典和集合 排序方法
    iOS 开发 OC编程 数组冒泡排序.图书管理
    iOS 开发 OC编程 属性和字符串练习
    iOS 开发 OC编程 属性和字符串
    iOS 开发 OC编程 便利构造器以及初始化方法
    iOS 开发 OC编程 方法的书写
    IOS 开发 OC编程 类和对象
    iOS 开发 c语言阶段考试题
  • 原文地址:https://www.cnblogs.com/oc-bowen/p/5170158.html
Copyright © 2011-2022 走看看