您的位置:首页 > 理论基础 > 计算机网络

14-网络-NSURLSession

2015-07-13 17:50 555 查看
一、简单介绍

1.get和post请求                   

要想使用GET和POST请求跟服务器进行交互,得先了解一个概念:
参数就是传递给服务器的具体数据,比如登录时的帐号、密码

GET和POST对比:GET和POST的主要区别表现在数据传递上

GET

1.在请求URL后面以?的形式跟上发给服务器的参数,多个参数之间用&隔开,比如http://ww.test.com/login?user14-网络name=123&pwd=234&type=JSON
2.GET请求的所有参数都直接暴露在URL中

3.由于浏览器和服务器对URL长度有限制,因此在URL后面附带的参数是有限制的,通常不能超过1KB

POST

发给服务器的参数全部放在请求体中

理论上,POST传递的数据量没有限制(具体还得看服务器的处理能力)

1.HTTP请求包结构:

2.HTTP响应包结构:

先给响应头,响应包以数据包形式一个一个的给

3.常见的响应状态码

二、第一种
创建 GET请求和POST请求方式
  //1.设置URL
   
NSURL *url = [NSURL
URLWithString:@"http://piao.163.com/m/cinema/list.html?app_id=1&mobileType=iPhone&ver=2.6&channel=appstore&deviceId=9E89CB6D-A62F-438C-8010-19278D46A8A6&apiVer=6&city=110000"];

   

    //2.创建请求

    NSMutableURLRequest
*request = [NSMutableURLRequest
requestWithURL:url];

    //请求方式(默认)

    request.HTTPMethod
=
@"GET";

      
//设置请求类型
   
//request.HTTPMethod
=
@"POST";
---------------------------------------------------------------------------------------------   
    //设置请求头
   
//只有一个key

    [request setValue:@"text/html; charset=utf-8"
forHTTPHeaderField:@"Content-Type"];

   
//会有多个key
    [request
addValue:@"text/html; charset=utf-8"
forHTTPHeaderField:@"Content-Type"];
---------------------------------------------------------------------------------------------

   
//设置请求体(NSString转换成NSData)
  
//request.HTTPBody
= [@"movie_id=43485"
dataUsingEncoding:NSUTF8StringEncoding]; 
   

    //3.创建会话对象

    NSURLSession
*session = [NSURLSession
sharedSession];

    //设置会话任务

   NSURLSessionDataTask
*task = [session
dataTaskWithRequest:request
completionHandler:^(NSData
*data,
NSURLResponse *response,
NSError *error) {

       

        if
(error == nil) {

           

            //拿到响应体(NSData转换成NSString)

            NSString
*responseBody = [[NSString
alloc]
initWithData:data
encoding:NSUTF8StringEncoding];

           

            //回到主线程设置数据

            [self.textView
performSelectorOnMainThread:@selector(setText:)
withObject:responseBody
waitUntilDone:NO];

           

            //获得响应头

            NSHTTPURLResponse
*responseHead = (NSHTTPURLResponse
*)response;

            NSDictionary
*dic = [responseHead
allHeaderFields];

            NSLog(@"%@", dic);

           

        }

       

    }];

   

    //4.开始会话
    [task
resume];
 
三、第二种NSURLSessionConfiguration创建GET请求和POST请求方式
//1.构造URL对象
   
NSURL *url = [NSURL
URLWithString:@"http://piao.163.com/m/cinema/list.html?app_id=1&mobileType=iPhone&ver=2.6&channel=appstore&deviceId=9E89CB6D-A62F-438C-8010-19278D46A8A6&apiVer=6&city=110000"];

   

   
/*

    

     ephemeralSessionConfiguration

     临时session配置,与默认配置相比,这个配置不会将缓存、cookie等存在本地,只会存在内存里,所以当程序退出时,所有的数据都会消失

    

     backgroundSessionConfiguration

     后台session配置,与默认配置类似,不同的是会在后台开启另一个线程来处理网络数据。

    

     */

   
//2.使用 defaultSessionConfiguration构造NSURLSessionConfiguration对象
   
NSURLSessionConfiguration *sionConfig = [NSURLSessionConfiguration
defaultSessionConfiguration];

    sionConfig.timeoutIntervalForRequest
=
30;

   

   
//设置属性

   
//requestCachePolicy:   缓存处理方式

   
//timeoutIntervalForRequest:  请求超时时间

   
//networkServiceType:  网络服务类型,网络流量,网络电话,语音,视频..

   
//allowsCellularAccess:  是否使用蜂窝网络

   
//3.构造会话对象
   
//获取主队列

    NSOperationQueue
*queue = [NSOperationQueue
mainQueue];

    NSURLSession
*session = [NSURLSession sessionWithConfiguration:sionConfig delegate:self
delegateQueue:queue];

   
//4.创建会话任务
   
NSURLSessionDataTask *task = [session dataTaskWithURL:url];

   
//5.开始会话
    [task
resume];

#pragma mark - NSURLSessionDataDelegate
----------------------------------------------------------------------------------------------------

//服务器已经开始响应时调用,已经得到响应头

- (void)URLSession:(NSURLSession
*)session

          dataTask:(NSURLSessionDataTask
*)dataTask

didReceiveResponse:(NSURLResponse
*)response

 completionHandler:(void
(^)(NSURLSessionResponseDisposition))completionHandler

{

   
//取出响应头里面的信息

    NSHTTPURLResponse
*responseHead = (NSHTTPURLResponse
*)response;

   

    NSLog(@"%@", responseHead);

   

   
//设置响应类型

    completionHandler(NSURLSessionResponseAllow);

}
---------------------------------------------------------------------------------------------

//网络数据请求完成调用

- (void)URLSession:(NSURLSession
*)session dataTask:(NSURLSessionDataTask
*)dataTask didReceiveData:(NSData
*)data

{

    NSString
*str = [[NSString
alloc]
initWithData:data
encoding:NSUTF8StringEncoding];

   

    self.textView.text
= str;

}
---------------------------------------------------------------------------------------------

//网络数据请求失败调用

- (void)URLSession:(NSURLSession
*)session task:(NSURLSessionTask
*)task didCompleteWithError:(NSError
*)error{

   
}
四、下载文件
----------------------------------------普通下载方式----------------------------------------------

//普通下载方式(缺点:不能监听下载进度)
- (IBAction)downLoad:(UIButton
*)sender {
 
//1.构造URL
NSURL *url = [NSURL
URLWithString:@"http://sc.111ttt.com/up/mp3/304296/937161E63A1D57484158C7464D7B50B7.mp3"];
//2.创建会话
NSURLSession *session = [NSURLSession
sharedSession];
  
//3.创建会话任务
NSURLSessionDownloadTask
*downTask = [session
downloadTaskWithURL:url
completionHandler:^(NSURL
*location,
NSURLResponse *response,
NSError *error) {
       

        if
(error == nil) {

           
//取得文件管理者

            NSFileManager
*fileM = [NSFileManager
defaultManager];
          
                 //移动到得位置和设置文件名称
        NSString *toPath = [NSHomeDirectory()
stringByAppendingPathComponent:@"/Documents/m.mp3"];
       
NSURL *url = [NSURL
fileURLWithPath:toPath];
           
       
//移动文件
        [fileM
moveItemAtURL:location
toURL:url
error:nil];
       
NSLog(@"下载完成");

        }else{

            NSLog(@"%@", error);

        }

       
    }];
   
//开始下载

    [downTask resume];
}
----------------------------------------有进度条下载方式-----------------------------------------
遵守协议<
NSURLSessionDownloadDelegate>
---------------------------------------------------------------------------------------------

成员变量
    //全局会话任务

    NSURLSessionDownloadTask
*_task;

   

   
//全局会话

    NSURLSession
*_session;

   

   
//记录取消那一刻的Data
    NSData *_data;
---------------------------------------------------------------------------------------------

//有进度的下载
- (IBAction)prosess:(UIButton
*)sender {

   

   
//1.构造URL

    NSURL
*url = [NSURL
URLWithString:@"http://sc.111ttt.com/up/mp3/304296/937161E63A1D57484158C7464D7B50B7.mp3"];

   

   
//2.创建会话配置对象

    NSURLSessionConfiguration
*config = [NSURLSessionConfiguration
defaultSessionConfiguration];

    config.timeoutIntervalForRequest
=
60;

   

   
//3.创建会话对象

    _session
= [NSURLSession
sessionWithConfiguration:config
delegate:self
delegateQueue:[NSOperationQueue
mainQueue]];

   

   
//4.创建会话任务

    _task
= [_session
downloadTaskWithURL:url];

   

   
//5.开始会话

    [_task
resume];
}
---------------------------------------------------------------------------------------------

#pragma mark - NSURLSessionDownloadDelegate
//下载时调用
- (void)URLSession:(NSURLSession
*)session downloadTask:(NSURLSessionDownloadTask
*)downloadTask

      didWriteData:(int64_t)bytesWritten

 totalBytesWritten:(int64_t)totalBytesWritten

totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite

{

    NSLog(@"%lld", bytesWritten);

   

   
//计算下载百分比

    CGFloat
value = totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;

   

    self.downProsess.progress
= value;

   

    self.downValue.text
= [NSString
stringWithFormat:@"%.2f%%", value *
100];

}
---------------------------------------------------------------------------------------------
//下载完成时调用

- (void)URLSession:(NSURLSession
*)session downloadTask:(NSURLSessionDownloadTask
*)downloadTask

didFinishDownloadingToURL:(NSURL
*)location

{

   
//取得文件管理者

    NSFileManager
*fileM = [NSFileManager
defaultManager];

   

   
//移动到得位置和设置文件名称

    NSString
*toPath = [NSHomeDirectory()
stringByAppendingPathComponent:@"/Documents/m.mp3"];

    NSLog(@"%@",toPath);

    NSURL
*url = [NSURL
fileURLWithPath:toPath];

   

   
//移动文件

    [fileM moveItemAtURL:location
toURL:url
error:nil];

   

    self.downValue.text
=
@"下载完成";

}

---------------------------------------------------------------------------------------------

断点续传
//暂停下载
- (IBAction)pause:(UIButton
*)sender {

   

   
//点击暂停时取消会话任务

    [_task
cancelByProducingResumeData:^(NSData
*resumeData) {

       
//j记录未传递的数据包

        _data
= resumeData;

       

    }];

   

}

---------------------------------------------------------------------------------------------
//恢复下载

- (IBAction)recover:(UIButton
*)sender {

   

   
//接着之前的Data数据开始会话任务

    _task
= [_session
downloadTaskWithResumeData:_data];

   

    [_task
resume];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: