NSURLSession详解

http
允许传输各种各样的数据
客户端——-服务器。
http协议规定:一个完整的由客户端发给服务器的http请求中包含以下内容
请求头:包含了对客户端的环境描述,客户端请求信息等
请求体:客户端发给服务器的具体数据,比如文件数据(post请求才会有)
客户端向服务器发送请求,服务器当作出响应
一个完整的http响应中包含以下内容:
响应头:包含了对服务器的描述,对返回数据的描述
响应体:服务器返回给客户端的具体数据,比如文件数据

get请求

- (void)creatGet
{
    //确定请求路径
    NSString *urlString = @"https://free-api.heweather.com/s6/weather/forecast?location=北京&key=e1066ff38a7346128d608626c1b1477d";
    //在使用url的时候,如果字符串中有中文,那么要对中文进行转码操作
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlString];
    //创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //创建会话对象
    NSURLSession *sharedSession = [NSURLSession sharedSession];
    //根据会话对象来创建请求task任务
    NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if(data && (error == nil)){
                        //网络访问成功,解析数据
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//                NSDictionary *dataDict = dict[@"data"];
            }
            else{
                //网络访问失败
                NSLog(@"error = %@", error);
            }
    } ];
    //执行发送请求任务
    [dataTask resume];//NSURLSession所有任务都是session发起的,默认所有的任务"挂起",需要resume

}

也可以简化为以下

  [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@""] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       // 处理服务器返回的数据,反序列化处理
        NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        //转换为oc中的对象
        //参数一:要解析的数据,二。解析数据时附加的选项,默认传0
        //NSJSONReadingMutableContainers = (1UL << 0),得到的对象是可变的,字典数组集合
       // NSJSONReadingMutableLeaves = (1UL << 1),//得到的对象中字符串是可变的
       //NSJSONReadingAllowFragments = (1UL << 2)//用的多,当返回的对象既不是字典也不是数组(null)[NSNull null]//空对象
        id obj = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        NSLog(@"%@--%@", [obj class], obj);
    }] resume];

post请求

- (void) creatpost
{
    NSURL *url = [NSURL URLWithString:@"Http://120.25.226.186:32812/login"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    //请求体
    NSString *bodyStr = @"username=123&pwd=123";
    request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析数据
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

         }];
    [dataTask resume];
}

代理方法

- (void)pleasedelegate
{       //确定请求路径
        NSString *urlString = @"https://free-api.heweather.com/s6/weather/forecast?location=北京&key=e1066ff38a7346128d608626c1b1477d";
        //在使用url的时候,如果字符串中有中文,那么要对中文进行转码操作
        urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSURL *url = [NSURL URLWithString:urlString];
        //创建请求对象
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        //创建会话对象
        /*参数说明
         第一个参数:配置信息(设置请求的,功能类似于NSURLRequest),defaultSesssionConfiguration默认
         第二个参数设置代理
         第三个参数:代理队列(线程)决定代理队列在哪个线程中调用
         */
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        //根据会话对象来创建请求task任务
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if(data && (error == nil)){
                //网络访问成功,解析数据
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                NSLog(@"%@",dict[@"HeWeather6"]);
                NSArray *dataArray = [[NSArray alloc]init];
                dataArray = dict[@"HeWeather6"];
                NSDictionary *dict1  = dataArray[0];
                NSLog(@"%@",dict1);

            }
            else{
                //网络访问失败
                NSLog(@"error = %@", error);
            }
        } ];
        //执行发送请求任务
        [dataTask resume];

}
//代理方法
//接收到服务器响应的时候会被调用
- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //需要通过调用completionHandler,告诉系统应如何处理服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);//告诉服务器返回接受的数据,还有几种可自行跳转到定义查看
//    typedef NS_ENUM(NSInteger, NSURLSessionResponseDisposition) {
//        NSURLSessionResponseCancel = 0,                                      /* Cancel the load, this is the same as -[task cancel] */
//        NSURLSessionResponseAllow = 1,                                       /* Allow the load to continue */
//        NSURLSessionResponseBecomeDownload = 2,                              /* Turn this request into a download */
//        NSURLSessionResponseBecomeStream API_AVAILABLE(macos(10.11), ios(9.0), watchos(2.0), tvos(9.0)) = 3,  /* Turn this task into a stream task */
//    } NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);

}
//接收到服务器返回数据的时候调用  该方法可能被调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data
{
    //拼接数据
    [self.resultdata appendData:data];
}
//请求完成或失败时调用,通过判断error是否有值来判断是否请求失败
- (void)URLSession:(NSURLSession *)session task:(nonnull NSURLSessionDataTask *)dataTask didCompleteWithError:(nullable NSError *)error
{

}

get和post对比
get和post的主要区别体现在数据上
get:* 在请求url后面以?的形式跟上发给服务器的参数,多个参数之间用&隔开,
由于浏览器和服务器对url长度有限制,因此在url后面附带的参数是有限制的,通常不能超过1kb
post:发给服务器的参数全部在请求体中,理论上,post传递的数据时没有限制的(具体还得看服务器的处理能力)

get和post的选择
如果要传递大量数据,比如文件上传,只能用post请求
get的安全性比post要差些,如果包含机密敏感信息,建议post
如果仅仅是 索取数据,建议用get
如果时增加,修改,删除数据,建议使用post

猜你喜欢

转载自blog.csdn.net/qiangshuting/article/details/81805966
今日推荐