NSURLSession和NSURLConnection

iOS9.0之后NSURLConnection被注销,采用NSURLSession,先介绍NSURLSession,然后介绍NSURLConnection

1.NSURLSession:

post请求:

    //1.
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
request.HTTPMethod=@"POST"; request.HTTPBody = [@"" dataUsingEncoding:NSUTF8StringEncoding]; //2.
NSURLSession *session=[NSURLSession sharedSession]; NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"NSURLSession加载数据。。。。post。。。。。%@",data); }];
//3.
[dataTask resume];

创建请求并设置代理delegate:(NSURLSessionDataDelegate)

    //1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"]; //2.创建请求对象
//请求对象内部默认已经包含了请求头和请求方法(GET)
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.获得会话对象,并设置代理
/*
第一个参数:会话对象的配置信息defaultSessionConfiguration 表示默认配置
第二个参数:谁成为代理,此处为控制器本身即self
第三个参数:队列,该队列决定代理方法在哪个线程中调用,可以传主队列|非主队列
[NSOperationQueue mainQueue] 主队列: 代理方法在主线程中调用
[[NSOperationQueue alloc]init] 非主队列: 代理方法在子线程中调用
*/
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]]; //4.根据会话对象创建一个Task(发送请求)
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request]; //5.执行任务
[dataTask resume];

delegate协议方法:

 //1.接收到服务器响应的时候调用该方法
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
//在该方法中可以得到响应头信息,即response
NSLog(@"didReceiveResponse--%@",[NSThread currentThread]); completionHandler(NSURLSessionResponseAllow); //注意:需要使用completionHandler回调告诉系统应该如何处理服务器返回的数据 //默认是取消的
/*
NSURLSessionResponseCancel = 0, 默认的处理方式,取消
NSURLSessionResponseAllow = 1, 接收服务器返回的数据
NSURLSessionResponseBecomeDownload = 2,变成一个下载请求
NSURLSessionResponseBecomeStream 变成一个流
*/
}
//2.接收到服务器返回数据的时候会调用该方法,如果数据较大那么该方法可能会调用多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
NSLog(@"didReceiveData--%@",[NSThread currentThread]); //拼接服务器返回的数据 }
//3.当请求完成(成功|失败)的时候会调用该方法,如果请求失败,则error有值
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"didCompleteWithError--%@",[NSThread currentThread]); if(error == nil)
{
//解析数据,JSON解析请参考 } }

2.NSURLConnection

普通请求:

 /*    //1.网址
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
//2.请求
NSURLRequest *request=[NSURLRequest requestWithURL:url];
//3.队列
NSOperationQueue *queue=[[NSOperationQueue alloc]init];
//4.发送异步请求
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError) {
NSString *content=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"加载成功:%@",content);
}];
*/
//同步发送,要放到另一个线程里,防止阻塞;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ), ^{ NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
NSURLResponse *response; NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];//&指的是指针;
NSString *content=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"NSURLConnection加载数据。。。。。。。:%@",content);
});

代理请求:(NSURLConnectionDataDelegate)

 NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]];
// NSURLResponse *response; [NSURLConnection connectionWithRequest:request delegate:self];

代理协议方法:

//
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"接到response");
}
//
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"接收数据"); }
//
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"接收数据完成"); }

参考网址:http://www.cnblogs.com/wendingding/p/5168772.html

上一篇:Vjudge题目杂集(1)


下一篇:超详细的FreeRTOS移植全教程——基于srm32