iOS之网络请求

iOS中遵循较为安全的HTTPS安全超文本协议,若想访问遵循HTTP协议的网页需要进行以下设置:

将代码<key>NSAppTransportSecurity</key>
     <dict>
        <key>NSAllowsArbitraryLoads</key>
             <true/>
    </dict>

复制到

路径下;

或者在info.plist文件中添加以下字段

请求方式分为GET和POST两种方式;每种方式又包含同步和异步两种形式;同步会是应用程序出现卡顿现象,这里只介绍异步的形式。

在iOS7之前使用NSURLConnection来进行网络的请求,iOS7之后前面的方法被重构,改为NSURLSession。先介绍NSURLConnection,虽然被重构但还是可以运行的:

#pragma mark - NSURLConnection - 异步get请求
- (IBAction)getAsynchronousRequest:(UIButton *)sender {
    //1.创建url
    NSURL *url = [NSURL URLWithString:GET_URL];//GET_URL是宏定义的网址,创建Header File,在其中宏定义网址。

宏定义:::::

#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"
    //2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //3.连接服务器
    //方法一:Block方法实现,//参数1:请求对象 //参数2:线程队列 //参数3:block
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            //4.解析
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"dic = %@", dic);
            //先开辟子线程解析数据
            //然后在主线程里刷新UI
        }   
    }];
 
    //方法二:使用delegate实现<NSURLConnectionDataDelegate>,将上面的3.4.两步替换为,同时使用先关代理方法
    //[NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma mark - NSURLConnectionDataDelegate相关的代理方法
//服务器开始响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self.resultData = [NSMutableData new];//初始化数据
}
//开始接收数据这个方法会重复执行,得到的每段数据拼接在一起就可以了
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.resultData appendData:data];
}
//结束服务器
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    //进行数据解析(根据url链接到的具体内容进行解析)
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"dic = %@", dic);
}
#pragma mark -NSURLConnection - 异步post请求
- (IBAction)postAsynchronousRequest:(UIButton *)sender {
    //1.创建url
    NSURL *url = [NSURL URLWithString:POST_URL];
    //2.创建请求
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
    //2.5设置body
    //创建一个链接字符串
    NSString *dataString = POST_BODY;
    //对连接字符串进行编码
    NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    //设置请求格式
    [mutableRequest setHTTPMethod:@"POST"];
    //设置请求体
    [mutableRequest setHTTPBody:postData];
    //3.链接服务器
    [NSURLConnection sendAsynchronousRequest:mutableRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        }
    }];
   }

#pragma mark - NSURLSession - get请求block实现
- (IBAction)getRequest:(UIButton *)sender {
    //方式一:使用block
    //1.创建url
    NSURL *url = [NSURL URLWithString:GET_URL];
    //2.创建请求NSURLRequest
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //2.创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    //3.创建task请求任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //4.解析相关的数据//这里block执行步骤比较靠后,不是在//2.创建session对象之后马上执行
        if (error == nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        }
    }];
    //5.核心步:启动任务【千万不要忘记】============
    //原因:NSURLSessionTask实例出来的任务处于挂起状态,如果不启动,不会走block中的实现部分
    [task resume];
#pragma mark - NSURLSession - get请求协议实现
    NSURL *url = [NSURL URLWithString:GET_URL];
    //2.创建session
    //参数1:模式的设置
    /*
     *  defaultSessionConfiguration  默认会话模式
     *  ephemeralSessionConfiguration  瞬时会话模式
     *  backgroundSessionConfigurationWithIdentifier 后台会话模式
     */
    //参数2:代理
    //参数3:主线程队列
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];//遵循协议<NSURLSessionDataDelegate>
    //3.创建task
    NSURLSessionDataTask *task = [session dataTaskWithURL:url];
    //4.启动
    [task resume];
#pragma mark - NSURLSessionDataDelegate协议的实现方法
//服务器开始响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    //允许服务器响应[在这个地方只有允许服务器响应了才会接收到数据]
    completionHandler(NSURLSessionResponseAllow);
    //初始化data稍后进行片段的拼接存储
    self.resultData = [NSMutableData data];
}
//接收数据拼接
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    //反复执行,然后拼接相关的片段
    [self.resultData appendData:data];
}
//数据接收完成,网络请求结束
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    //解析
    if (error == nil) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"dic = %@", dic);
    }
}

#pragma mark - NSURLSession - post请求
- (IBAction)postRequest:(UIButton *)sender {
    //1.创建url
    NSURL *url = [NSURL URLWithString:POST_URL];
    //2.创建请求
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:url];
  //2.5核心设置body
    NSString *bodyString = POST_BODY;
    NSData *postData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    [mutableRequest setHTTPMethod:@"POST"];
    [mutableRequest setHTTPBody:postData];
    //3.创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    //4.创建task对象
    NSURLSessionDataTask *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 = %@", dic);
        }
    }];
    //6.启动任务
    [task resume];
}



 

posted @ 2016-05-14 14:48  吾悠南山  阅读(221)  评论(0编辑  收藏  举报