_水丹青

iOS---NSURLConnection与NSURLSession数据解析

数据请求

一、工作原理

URL全程Uniform Resource Locator(统一资源定位符)

URL基本格式: 协议://主机地址/路径

协议分为两种: HTTP协议:超文本传输协议

        HTTPS协议:安全超文本传输协议

SSL:安全保密协议, 运行在TCP/IP层之上、应用层之下, 为应用程序提供加密数据通道

HTTP和HTTPS异同:

HTTPS需要到ca申请证书, 一般免费证书很少, 需要交费.

HTTP是超文本传输协议, 信息是明文传输, HTTPS则是具有安全性的加密传输协议

HTTP和HTTPS使用的是完全不同的链接方式, 用的端口也不一样, 前者是80, 后者是443.

HTTP的链接是无状态的

HTTPS的协议是由SSL+HTTP协议构建的可进行加密传输, 身份认证的网络协议, 相对HTTP安全

二、请求方式

○ GET

通过网址字符串

网址字符串最多255字节

传输的数据显示在网址里类似于密码的明文输入, 直接可见

○ POST

通过data

使用NSData, 容量超过1G

数据被转成NSData(二进制数据), 类似于密码的密文输入, 无法直接读取

 

三、iOS实现网络编程

URL.h

#ifndef URL_h
#define URL_h

#define GET_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define POST_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"

#define POST_BODY @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#endif /* URL_h */

 ViewController.m

#import "ViewController.h"
#import "URL.h"
@interface ViewController ()<NSURLConnectionDataDelegate>

//用来存储数据
@property (nonatomic, strong)NSMutableData *resultData;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

#pragma mark - 同步get请求
- (IBAction)getSynchronousRequest:(id)sender {
    
    //1.创建URL
    NSURL *url = [NSURL URLWithString:GET_URL];
    
    //2.根据url创建具体的请求
    //参数1: 统一资源定位符 url
    //参数2: 缓存策略(枚举值)
    //参数3: 设置延迟时间, 如果超时请求终止
    
    /*
     NSURLRequestUseProtocolCachePolicy//(基础策略)
     
     NSURLRequestReloadIgnoringLocalCacheData//(忽略本地缓存)
     
     NSURLRequestReturnCacheDataElseLoad//(首先使用缓存,如果没有本地缓存,才从原地址下载)
     
     NSURLRequestReturnCacheDataDontLoad//(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作) www.2cto.com
     
     NSURLRequestReloadIgnoringLocalAndRemoteCacheData//(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)
     
     NSURLRequestReloadRevalidatingCacheData//(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)
     */
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20];
    
    //3: 链接服务器 [NSURLConnection在iOS9之后被弃用, 在以后的开发中很少见]
    //参数1: 请求对象
    //参数2: 存储一些网络请求的信息(一般为包体) 一般为nil
    //参数3: 错误信息
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    //进行json数据解析
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@", resultDic);
}

#pragma mark - 同步post请求
- (IBAction)postSynchronousRequest:(id)sender {
    
    //1.创建url
    NSURL *url = [NSURL URLWithString:POST_URL];
    
    //2.创建网络请求
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
    //2.1 设置body
    NSString *dataString = POST_BODY;
    //创建一个连接字符串 (这个内容在以后的开发中接口文档都有标注)
    
    //对连接字符串进行编码(这一步千万不能忘记)
    NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    
    //设置请求格式为POST请求
    [mutableRequest setHTTPMethod:@"POST"];
    
    //设置请求体(body)
    [mutableRequest setHTTPBody:postData];
    
    //3.连接服务器
    NSData *data = [NSURLConnection sendSynchronousRequest:mutableRequest returningResponse:nil error:nil];
    
    //4.json解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    NSLog(@"dic = %@", dic);
}
#pragma mark - GET异步请求
- (IBAction)getAsynchronousRequest:(id)sender {
    
    //1.创建url
    NSURL *url = [NSURL URLWithString:GET_URL];
    
    //2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //3.连接服务器
    
    //方法一: Block实现
    //第一个参数: 请求对象
    //第二个参数: 线程队列
    /*
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        //resonse: 携带的接口信息
        //data: 请求下来的数据, 会使用到
        //connectionError: 错误信息
        
        if (connectionError == nil) {
            //4.解析
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            
            NSLog(@"%@", dic);
            
            //先开辟子线程解析数据
            //然后在主线程里刷新UI
            
        }
        
    }];
     */
    
    //方法二: 使用delegate实现
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    
}

#pragma mark - NSURLConnectionDataDelegate相关的代理方法
//服务器开始响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    //初始化数据
    self.resultData = [NSMutableData data];
    
}

//开始接收数据
//这个方法会重复执行, 得到的每段数据拼接在一起就可以了
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    [self.resultData appendData:data];
}

//结束服务器
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    //进行数据解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
    
    NSLog(@"%@", dic);
}
#pragma mark - POST异步请求
- (IBAction)postAsynchronousRequest:(id)sender {
    
    //1.创建url
    NSURL *url = [NSURL URLWithString:POST_URL];
    //2.创建网络请求
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
    
    //2.1 设置body
    NSString *dataString = POST_BODY;
    
    //创建一个连接字符串
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    
    [mutableRequest setHTTPMethod:@"POST"];
    [mutableRequest setHTTPBody:data];
    
    //3.连接服务器
    [NSURLConnection sendAsynchronousRequest:mutableRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            //4.数据解析
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@", dict);
        }
    }];
    
    [NSURLConnection connectionWithRequest:mutableRequest delegate:self];
}

Session -----

GET请求:

//1.创建url
    NSURL *url = [NSURL URLWithString:GET_URL];
    
    //2.创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //3.创建task请求任务
    //NSURLSession是基于任务去完成相关事件的
    //NSURLSessionTask所有的任务均放在此处实现
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //4.解析相关的数据
        if (error == nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            
            NSLog(@"%@", dic);
            
        }
    }];
     
    
    //5.核心步骤: 启动任务: [千万不能忘记]
    //原因: NSURLSessionTask实例出来的任务处于挂起状态, 如果不启动, 不会走block中的实现内容
    [task resume];

 POST请求:

//1.创建url
    NSURL *url = [NSURL URLWithString:POST_URL];
    
    //2.创建请求
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
    
    //2.1 核心设置body
    NSString *bodyString = POST_BODY;
    
    NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    [mutableRequest setHTTPMethod:@"POST"];
    [mutableRequest setHTTPBody:data];
    
    //3.创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //4.创建task
    NSURLSessionTask *task = [session dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        //5.解析
        if (error == nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@", dic);
        }
    }];
    
    //6.启动任务
    [task resume];

 

posted on 2016-05-11 23:30  大一号  阅读(218)  评论(0)    收藏  举报

导航