首页投稿(暂停使用,暂停投稿)程序员iOS学习笔记

网络请求

2016-07-04  本文已影响668人  钎探穗

①:HTTP协议,永远都是由客户端发送请求,服务器返回数据
②:HTTP协议是无状态的,同一个客户端的这次请求和上一次没有对应关系
③:HTTPS协议需要到CA(沃通,由受信任数字证书颁发机构,在验证服务器身份后,具有服务器身份验证和数据传输加密功能,因其需要配置在服务器上,所有也称SSL服务器,或者SSL证书)申请书,一般免费证书很少,需要交费

说到GET,POST,那么他们的区别是什么呢?

  • GET与POST方法有以下区别:

上面说了这么多,下面举例来看看.
首先使用http请求
要在Info.plist里边作一下修改


4FE5AF3B-9FA2-4D7C-82AB-FB0D4724C97D.png
#pragma mark----getSession(block方法)-------
- (void)getSession{
    NSURL *url = [NSURL URLWithString:GET_URL];
    //创建session对象
    //NSURLSession 是基于任务完成相关的事件,所有内容都放在这个任务里
    NSURLSession *session = [NSURLSession sharedSession];//使用系统提供的全局的NSURLSession 的一个单例
    //创建task任务对象,NSURLSessionTask就是NSURLSession任务执行的对象
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
 
        if (!error) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            NSLog(@"getSession:%@",dic);
 //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新UI
                //[self.tableView reloadData];
            });
        }
    }];
    //执行任务(一定要执行)
    [task resume];
}
#pragma mark----postSession(block)-------
- (void)postSession{
   //创建URL
   NSURL *url = [NSURL URLWithString:POST_URL];
   //创建请求(post请求必须初始化为可变请求)
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
     //创建body
   NSString *dataString = POST_BODY;
   //转码
   NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
   [request setHTTPBody:data];
   [request setHTTPMethod:@"POST"];
//创建session对象
   NSURLSession *session = [NSURLSession sharedSession];
   //创建任务
   NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       if (!error) {
           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
           NSLog(@"postsession :%@",dic);
//回到主线程刷新表格
           dispatch_async(dispatch_get_main_queue(), ^{
               //刷新UI
               //[self.tableView reloadData];
           });
       }
 
   }];
   [task resume];
}
#pragma mark-----getSession  代理模式(postSession同理适用)----
- (void)requestData8{
//NSURLSession代理人的属性是只读的
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];
//NSURLSessionTask的子类对象
    NSURLSessionDataTask *task = [session dataTaskWithURL:url];
    [task resume];
}

#pragma mark -------NSURLSessionDataDelegate协议方法(前提还要遵循NSURLSessionDataDelegate协议)-------

//服务器开始响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
//NSURLSession的代理协议里面必须设置允许继续请求,才会继续响应服务器
    completionHandler(NSURLSessionResponseAllow);
    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(@"data=====%@",self.resultData);
        NSLog(@"dic8=====%@",dic);
 //回到主线程刷新表格
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新UI
                //[self.tableView reloadData];
            });
    }

}

GET请求和POST请求方式的比较:

  • 不同点:

除了上面的方法外GET异步和POST异步还有其他方法,只是不建议使用了.可做了解.

#pragma mark----异步GET-------
- (void)getYB{
 //创建URL
    NSURL *url = [NSURL URLWithString:GET_URL];
    //创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //接收数据
#pragma mark---第一种方法block
//    //方法1:block
//    /*
//     sendAsynchronousRequest:<#(nonnull NSURLRequest *)#> queue:<#(nonnull NSOperationQueue *)#> completionHandler:<#^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError)handler#>
//     参数1:请求对象
//     参数2:NSOperationQueue mainQueue,线程队列,让block在哪个线程中执行,主队列也叫串行队列
//     参数3:response:携带的接口信息.data:请求回来的数据.connectionError:错误信息
//     */
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//        //进行判断,判断错误信息是否为空
//        if (!connectionError) {
//            //进行解析
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
//            NSLog(@"异步GET-------%@",dic);
//        }
//    }];
#pragma mark---第二种方法代理-----
    [NSURLConnection connectionWithRequest:request delegate:self];
}
#pragma mark---NSURLConnectionDataDelegate代理方法----
//服务器开始响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    //初始化数据源
    self.resultdata = [NSMutableData data];
}
//开始接收数据
//这个方法重复执行,将每次遇到的每段数据拼接到self.resultdata
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"+++++++%@",self.resultdata);
    NSLog(@"===========%@",data);
    [self.resultdata appendData:data];
}
//结束服务器
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//进行解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultdata options:(NSJSONReadingAllowFragments) error:nil];
    NSLog(@"GET异步代理:%@",dic);

}

下边也粗略说下同步连接,仅了解.因为同步连接,程序容易出现卡死现象.

#pragma mark----同步GET-------
- (void)getTB{
//创建URL(使用NSURL对象)
    NSURL *url = [NSURL URLWithString:GET_URL];
    //根据URL创建具体请求方式
    /*
     requestWithURL:<#(nonnull NSURL *)#> cachePolicy:<#(NSURLRequestCachePolicy)#> timeoutInterval:<#(NSTimeInterval)#>
     参数1:接口
     参数2:缓存策略
     NSURLRequestUseProtocolCachePolicy(基础策略):默认缓存策略,如果缓存不存在,直接从服务器获取
     NSURLRequestReloadIgnoringLocalCacheData:忽略本地缓存,直接从服务器获取
     NSURLRequestReturnCacheDataElseLoad:优先加载缓存,如果没有就在原地址中加载
     NSURLRequestReturnCacheDataDontLoad:使用本地缓存,如果没有,也不去服务器加载,导致请求失败,一般用于离线操作
    参数3:设置一个延时时间,如果超过这个时间,那么请求终止(连接超时.单位:秒)
     */
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30];
    //接收网络数据(使用NSData对象)
    /*
     sendSynchronousRequest:<#(nonnull NSURLRequest *)#> returningResponse:<#(NSURLResponse *__autoreleasing  _Nullable * _Nullable)#> error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>
     参数1:请求对象
     参数2:存储一些网络请求信息,一般为nil,有包体的放包体
     参数3:错误信息
     
     */
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//    NSLog(@"---------------------------%@",data);
    
    //JSON解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
    NSLog(@"GET同步:%@",dic);
    
    
}

#pragma mark----同步POST-------
- (void)postTB{
    //创建URL
    NSURL *url1 = [NSURL URLWithString:POST_URL];
//创建网络请求(post请求必须初始化为可变请求
    NSMutableURLRequest *mutablerequest = [NSMutableURLRequest requestWithURL:url1];
    //设置BODY
    //创建字符串
    NSString *dataString = POST_BODY;
    //使用NSData类型接收转码后的BODY(UTF8)
    NSData *postdata = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    //设置请求格式为post
    [mutablerequest setHTTPMethod:@"POST"];
    //设置请求体
    [mutablerequest setHTTPBody:postdata];
    //接收数据
    NSData *data = [NSURLConnection sendSynchronousRequest:mutablerequest returningResponse:nil error:NULL];
    //解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
    NSLog(@"post同步---------%@",dic);

    
}

上一篇 下一篇

猜你喜欢

热点阅读