NSURLConnection网络处理和NSURLSession网络处理

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()<NSURLConnectionDataDelegate>
 4 @property (nonatomic,strong) NSMutableData *receiveData;
 5 @end
 6 
 7 @implementation ViewController
 8 //getter方法
 9 -(NSMutableData *)receiveData
10 {
11     if (_receiveData == nil) {
12         _receiveData = [NSMutableData data];
13     }
14     return _receiveData;
15 }
16 - (void)viewDidLoad {
17     [super viewDidLoad];
18 //    //创建URL对象
19 //    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/s?wd=wtb"];
20 //    NSLog(@"%@",url);
21 //    //协议
22 //    NSLog(@"scheme:%@",url.scheme);
23 //    //域名
24 //    NSLog(@"HOST:%@",url.host);
25 //    //Query查询语句,是问号之后的语句
26 //    NSLog(@"query:%@",url.query);
27 //    //Path路径
28 //    NSLog(@"path:%@",url.path);
29 //    
30 //    //创建
31 //    NSURLRequest *request = [NSURLRequest requestWithURL:url];
32     //使用网络链接类NSURLConnection发送网络请求
33     
34     //同步的网络请求
35 //   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
36 //    NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
37 //    
38 //    NSURLRequest *request1 = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
39     
40     //创建url对象
41     NSURL *url2 = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];
42     //创建NSURLRequest对象
43     NSURLRequest *request2 = [NSURLRequest requestWithURL:url2];
44     //使用NSURLConnection网络连接器发送异步代理请求
45 //    [NSURLConnection connectionWithRequest:request2 delegate:self];
46     
47     //异步Block请求,使用Block的时候,代理不起作用,二者只能存在其一,但是session可以,session只有异步,没有同步
48     [NSURLConnection sendAsynchronousRequest:request2 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
49         NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
50         NSLog(@"%@",str);
51     }];
52     
53     
54 }
55 //开始发送请求
56 -(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
57 {
58     return request;
59 }
60 //接收到服务器响应Response
61 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
62 {
63     NSLog(@"接受的响应:%@",response);
64     //HTTPResponse
65     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
66     long long length = [httpResponse expectedContentLength];
67     NSLog(@"%lld",length);
68 }
69 //接收到data
70 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
71 {
72     [self.receiveData appendData:data];
73     NSLog(@"%ld",data.length);
74 }
75 //接收数据完成
76 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
77 {
78     NSLog(@"接收完成");
79     NSString *str = [[NSString alloc] initWithData:self.receiveData encoding:NSUTF8StringEncoding];
80     NSLog(@"%@",str);
81 }
82 
83 //请求出错
84 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
85 
86 {
87     NSLog(@"请求出错");
88     
89 }
90 - (void)didReceiveMemoryWarning {
91     [super didReceiveMemoryWarning];
92     // Dispose of any resources that can be recreated.
93 }
94 
95 @end

2.NSURLSession网络处理,都有的是代理和block ,session以后把同步删了,想同步用过期的NSURLSesssion

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()<NSURLSessionDataDelegate>
 4 
 5 @end
 6 
 7 @implementation ViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     //由于浏览器不支持中文,所以要进行汉字转码
12     NSString *str = @"http://www.baidu.com/s?wd=滑板鞋";
13     NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:str]];
14     NSURL *url = [NSURL URLWithString:result];
15     
16     //创建request
17     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
18 //    //异步block请求
19 //    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
20 //        NSLog(@"%@",data);
21 //        NSLog(@"%@",connectionError);
22 //    }];
23     
24     //创建数据请求任务
25 //    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
26 //        NSLog(@"%@",error);
27 //    }];
28 //    //恢复请求任务
29 //    [dataTask resume];
30     
31     //创建一个POST请求
32     NSURL *url2= [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
33     //创建请求request
34     NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url2];
35     //设置请求方式为POST,添加body体
36     mRequest.HTTPMethod = @"POST";
37     mRequest.HTTPBody = [@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
38     //
39 //    NSURLSessionDataTask *postDataTask = [[NSURLSession sharedSession] dataTaskWithRequest:mRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
40 //        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
41 //        NSLog(@"%@",str);
42 //    }];
43 //    [postDataTask resume];
44     
45     
46     
47     //使用NSURLSessionDataDelegate
48     NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
49 //    //创建数据请求任务
50     
51     //1.block
52 //    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
53 //        NSLog(@"%@",data);
54 //    }];
55 //    //
56 //    [dataTask resume];
57     
58     //2.代理
59     NSURLSessionDataTask *dataTask =[session dataTaskWithRequest:mRequest];
60     [dataTask resume];
61     
62 }
63 //接收服务器响应
64 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
65 {
66     NSLog(@"接收到服务器响应");
67     //允许服务器继续发送数据
68     completionHandler(NSURLSessionResponseAllow);
69 }
70 //接收到数据
71 -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
72 {
73     NSLog(@"%ld",data.length);
74 }
75 //接收数据完成
76 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
77 
78 {
79     NSLog(@"接收数据完成");
80 
81 }
82 
83 - (void)didReceiveMemoryWarning {
84     [super didReceiveMemoryWarning];
85     // Dispose of any resources that can be recreated.
86 }

 

posted @ 2016-03-17 17:44  恒远也  阅读(220)  评论(0编辑  收藏  举报