标签:
一、NSURLConnection的常用类
(1)NSURL:请求地址
(2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法、请求头、请求体....
(3)NSMutableURLRequest:NSURLRequest的子类
(4)NSURLConnection:负责发送请求,建立客户端和服务器的连接。发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据
使用NSURLConnection发送请求的步骤很简单
(1)创建一个NSURL对象,设置请求路径(设置请求路径)
(2)传入NSURL创建一个NSURLRequest对象,设置请求头和请求体(创建请求对象)
(3)使用NSURLConnection发送NSURLRequest(发送请求)

2.代码示例
(1)发送请求的三个步骤:
 1 //
 2 //  YYViewController.m
 3 //  01-NSURLConnection的使用(GET)
 4 //
 5 //  Created by apple on 14-6-28.
 6 //  Copyright (c) 2014年 itcase. All rights reserved.
 7 //
 8 
 9 #import "YYViewController.h"
10 #import "MBProgressHUD+MJ.h"
11 
12 @interface YYViewController ()
13 @property (weak, nonatomic) IBOutlet UITextField *username;
14 @property (weak, nonatomic) IBOutlet UITextField *pwd;
15 - (IBAction)login;
16 
17 @end
18 
19 @implementation YYViewController
20 
21 - (IBAction)login {
22 //    1.提前的表单验证
23     if (self.username.text.length==0) {
24         [MBProgressHUD showError:@"请输入用户名"];
25         return;
26     }
27     if (self.pwd.text.length==0) {
28         [MBProgressHUD showError:@"请输入密码"];
29         return;
30     }
31 //    2.发送请求给服务器(带上账号和密码)
32     //添加一个遮罩,禁止用户操作
33 //    [MBProgressHUD showMessage:@"正在努力加载中...."];
34 //    GET请求:请求行\请求头\请求体
35 //
36 //    1.设置请求路径
37     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
38     NSURL *url=[NSURL URLWithString:urlStr];
39 //    2.创建请求对象
40     NSURLRequest *request=[NSURLRequest requestWithURL:url];
41 //    3.发送请求
42     //发送同步请求,在主线程执行
43     NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
44     //(一直在等待服务器返回数据,这行代码会卡住,如果服务器没有返回数据,那么在主线程UI会卡住不能继续执行操作)
45     NSLog(@"--%d--",data.length);
46 }
47 @end
模拟器情况:

打印服务器返回的信息:

 1 //
 2 //  YYViewController.m
 3 //  01-NSURLConnection的使用(GET)
 4 //
 5 //  Created by apple on 14-6-28.
 6 //  Copyright (c) 2014年 itcase. All rights reserved.
 7 //
 8 
 9 #import "YYViewController.h"
10 #import "MBProgressHUD+MJ.h"
11 
12 @interface YYViewController ()
13 @property (weak, nonatomic) IBOutlet UITextField *username;
14 @property (weak, nonatomic) IBOutlet UITextField *pwd;
15 - (IBAction)login;
16 
17 @end
18 
19 @implementation YYViewController
20 
21 - (IBAction)login {
22 //    1.提前的表单验证
23     if (self.username.text.length==0) {
24         [MBProgressHUD showError:@"请输入用户名"];
25         return;
26     }
27     if (self.pwd.text.length==0) {
28         [MBProgressHUD showError:@"请输入密码"];
29         return;
30     }
31 //    2.发送请求给服务器(带上账号和密码)
32     //添加一个遮罩,禁止用户操作
33     [MBProgressHUD showMessage:@"正在努力加载中...."];
34 
35 //
36 //    1.设置请求路径
37     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
38     NSURL *url=[NSURL URLWithString:urlStr];
39     
40 //    2.创建请求对象
41     NSURLRequest *request=[NSURLRequest requestWithURL:url];
42     
43 //    3.发送请求
44     //3.1发送同步请求,在主线程执行
45 //    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
46     //(一直在等待服务器返回数据,这行代码会卡住,如果服务器没有返回数据,那么在主线程UI会卡住不能继续执行操作)
47     
48     //3.1发送异步请求
49     //创建一个队列(默认添加到该队列中的任务异步执行)
50 //    NSOperationQueue *queue=[[NSOperationQueue alloc]init];
51     //获取一个主队列
52     NSOperationQueue *queue=[NSOperationQueue mainQueue];
53     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
54         NSLog(@"--block回调数据--%@---%d", [NSThread currentThread],data.length);
55         //隐藏HUD,刷新UI的操作一定要放在主线程执行
56         [MBProgressHUD hideHUD];
57         
58         //解析data
59         /*
60         {"success":"登录成功"}
61         {"error":"用户名不存在"}
62         {"error":"密码不正确"}
63          */
64         NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
65         NSLog(@"%@",dict);
66         
67         //判断后,在界面提示登录信息
68         NSString *error=dict[@"error"];
69         if (error) {
70             [MBProgressHUD showError:error];
71         }else
72         {
73             NSString *success=dict[@"success"];
74             [MBProgressHUD showSuccess:success];
75         }
76     }];
77     NSLog(@"请求发送完毕");
78 }
79 @end
模拟器情况(注意这里使用了第三方框架):

打印查看:

 1  NSOperationQueue *queue=[NSOperationQueue mainQueue];
 2     [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
 3         //当请求结束的时候调用(有两种结果,一个是成功拿到数据,也可能没有拿到数据,请求失败)
 4         NSLog(@"--block回调数据--%@---%d", [NSThread currentThread],data.length);
 5         //隐藏HUD,刷新UI的操作一定要放在主线程执行
 6         [MBProgressHUD hideHUD];
 7         
 8         //解析data
 9         /*
10         {"success":"登录成功"}
11         {"error":"用户名不存在"}
12         {"error":"密码不正确"}
13          */
14         if (data) {//请求成功
15             NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
16             NSLog(@"%@",dict);
17             
18             //判断后,在界面提示登录信息
19             NSString *error=dict[@"error"];
20             if (error) {
21                 [MBProgressHUD showError:error];
22             }else
23             {
24                 NSString *success=dict[@"success"];
25                 [MBProgressHUD showSuccess:success];
26             }
27         }else   //请求失败
28         {
29             [MBProgressHUD showError:@"网络繁忙,请稍后重试!"];
30         }
31      
32     }];
   //解析data
        /*
        {"success":"登录成功"}
        {"error":"用户名不存在"}
        {"error":"密码不正确"}
         */
要监听服务器返回的data,所以使用<NSURLConnectionDataDelegate>协议
常见大代理方法如下:
 1 #pragma mark- NSURLConnectionDataDelegate代理方法
 2 
 3 //当接收到服务器的响应(连通了服务器)时会调用
 4 
 5 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 6 
 7 //当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)
 8 
 9 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
10 
11 //当服务器的数据加载完毕时就会调用
12 
13 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
14 
15 //请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)
16 
17 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
使用异步方法发送get请求的代码示例:
  1 //
  2 //  YYViewController.m
  3 //  01-NSURLConnection的使用(GET)
  4 //
  5 //  Created by apple on 14-6-28.
  6 //  Copyright (c) 2014年 itcase. All rights reserved.
  7 //
  8 
  9 #import "YYViewController.h"
 10 #import "MBProgressHUD+MJ.h"
 11 
 12 @interface YYViewController ()<NSURLConnectionDataDelegate>
 13 @property (weak, nonatomic) IBOutlet UITextField *username;
 14 @property (weak, nonatomic) IBOutlet UITextField *pwd;
 15 @property(nonatomic,strong)NSMutableData *responseData;
 16 - (IBAction)login;
 17 
 18 @end
 19 
 20 @implementation YYViewController
 21 
 22 - (IBAction)login {
 23 //    1.提前的表单验证
 24     if (self.username.text.length==0) {
 25         [MBProgressHUD showError:@"请输入用户名"];
 26         return;
 27     }
 28     if (self.pwd.text.length==0) {
 29         [MBProgressHUD showError:@"请输入密码"];
 30         return;
 31     }
 32 //    2.发送请求给服务器(带上账号和密码)
 33     //添加一个遮罩,禁止用户操作
 34     [MBProgressHUD showMessage:@"正在努力加载中...."];
 35 
 36 //
 37 //   2.1设置请求路径
 38     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
 39     NSURL *url=[NSURL URLWithString:urlStr];
 40     
 41 //   2.2创建请求对象
 42 //    NSURLRequest *request=[NSURLRequest requestWithURL:url];//默认就是GET请求
 43     //设置请求超时
 44     NSMutableURLRequest *request=[NSMutableURLRequest  requestWithURL:url];
 45     request.timeoutInterval=5.0;
 46     
 47 //   2.3.发送请求
 48  //使用代理发送异步请求(通常应用于文件下载)
 49     NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
 50     [conn start];
 51     NSLog(@"已经发出请求---");
 52 }
 53 
 54 #pragma mark- NSURLConnectionDataDelegate代理方法
 55 /*
 56  *当接收到服务器的响应(连通了服务器)时会调用
 57  */
 58 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
 59 {
 60     NSLog(@"接收到服务器的响应");
 61     //初始化数据
 62     self.responseData=[NSMutableData data];
 63 }
 64 
 65 /*
 66 *当接收到服务器的数据时会调用(可能会被调用多次,每次只传递部分数据)
 67 */
 68 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
 69 {
 70     NSLog(@"接收到服务器的数据");
 71     //拼接数据
 72     [self.responseData appendData:data];
 73         NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
 74 }
 75 
 76 /*
 77  *当服务器的数据加载完毕时就会调用
 78  */
 79 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
 80 {
 81     NSLog(@"服务器的数据加载完毕");
 82     //隐藏HUD
 83     [MBProgressHUD hideHUD];
 84     
 85     //处理服务器返回的所有数据
 86     NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:nil];
 87     
 88     //判断后,在界面提示登录信息
 89     NSString *error=dict[@"error"];
 90     if (error) {
 91         [MBProgressHUD showError:error];
 92     }else
 93     {
 94         NSString *success=dict[@"success"];
 95         [MBProgressHUD showSuccess:success];
 96     }
 97     NSLog(@"%d---%@--",self.responseData.length,[NSThread currentThread]);
 98 }
 99 /*
100  *请求错误(失败)的时候调用(请求超时\断网\没有网\,一般指客户端错误)
101  */
102 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
103 {
104 //     NSLog(@"请求错误");
105     //隐藏HUD
106     [MBProgressHUD hideHUD];
107     [MBProgressHUD showError:@"网络繁忙,请稍后重试!"];
108 }
109 @end
打印查看:

补充:
(1)数据的处理
在didReceiveData:方法中,拼接接收到的所有数据,等所有数据都拿到后,在connectionDidFinishLoading:方法中进行处理
(2)网络延迟
在做网络开发的时候,一定要考虑到网络延迟情况的处理,可以在服务器的代码设置一个断点模拟。
在服务器代码的登录方法中设置断点

设置请求的最大延迟
 
 
模拟器情况:

打印查看:

三、NSMutableURLRequest
NSMutableURLRequest是NSURLRequest的子类,常用方法有
设置请求超时等待时间(超过这个时间就算超时,请求失败)- (void)setTimeoutInterval:(NSTimeInterval)seconds;
设置请求方法(比如GET和POST)- (void)setHTTPMethod:(NSString *)method;
设置请求体- (void)setHTTPBody:(NSData *)data;
设置请求头- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
四:NSURLSeccssion
基本使用
1 // 任务:任何请求都是一个任务 2 // NSURLSessionDataTask : 普通的GET\POST请求 3 // NSURLSessionDownloadTask : 文件下载 4 // NSURLSessionUploadTask : 文件上传 5 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 6 { 7 [self downloadTask2]; 8 } 9 10 - (void)downloadTask2 11 { 12 NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; 13 14 // 1.得到session对象 15 NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 16 17 // 2.创建一个下载task 18 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/test.mp4"]; 19 NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url]; 20 21 // 3.开始任务 22 [task resume]; 23 24 // 如果给下载任务设置了completionHandler这个block,也实现了下载的代理方法,优先执行block 25 } 26 27 #pragma mark - NSURLSessionDownloadDelegate 28 /** 29 * 下载完毕后调用 30 * 31 * @param location 临时文件的路径(下载好的文件) 32 */ 33 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location 34 { 35 // location : 临时文件的路径(下载好的文件) 36 37 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 38 // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致 39 40 NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; 41 42 // 将临时文件剪切或者复制Caches文件夹 43 NSFileManager *mgr = [NSFileManager defaultManager]; 44 45 // AtPath : 剪切前的文件路径 46 // ToPath : 剪切后的文件路径 47 [mgr moveItemAtPath:location.path toPath:file error:nil]; 48 } 49 50 /** 51 * 恢复下载时调用 52 */ 53 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes 54 { 55 56 } 57 58 59 /** 60 * 每当下载完(写完)一部分时就会调用(可能会被调用多次) 61 * 62 * @param bytesWritten 这次调用写了多少 63 * @param totalBytesWritten 累计写了多少长度到沙盒中了 64 * @param totalBytesExpectedToWrite 文件的总长度 65 */ 66 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite 67 { 68 double progress = (double)totalBytesWritten / totalBytesExpectedToWrite; 69 NSLog(@"下载进度---%f", progress); 70 } 71 72 #pragma mark ------------------------------------------------------------------ 73 /** 74 * 下载任务:不能看到下载进度 75 */ 76 - (void)downloadTask 77 { 78 // 1.得到session对象 79 NSURLSession *session = [NSURLSession sharedSession]; 80 81 // 2.创建一个下载task 82 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/test.mp4"]; 83 NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { 84 // location : 临时文件的路径(下载好的文件) 85 86 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 87 // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致 88 NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename]; 89 90 // 将临时文件剪切或者复制Caches文件夹 91 NSFileManager *mgr = [NSFileManager defaultManager]; 92 93 // AtPath : 剪切前的文件路径 94 // ToPath : 剪切后的文件路径 95 [mgr moveItemAtPath:location.path toPath:file error:nil]; 96 }]; 97 98 // 3.开始任务 99 [task resume]; 100 } 101 102 - (void)dataTask 103 { 104 // 1.得到session对象 105 NSURLSession *session = [NSURLSession sharedSession]; 106 107 // 2.创建一个task,任务 108 // NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"]; 109 // NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 110 // NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; 111 // NSLog(@"----%@", dict); 112 // }]; 113 114 NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/MJServer/login"]; 115 116 // 创建一个请求 117 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 118 request.HTTPMethod = @"POST"; 119 // 设置请求体 120 request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding]; 121 122 NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 123 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil]; 124 NSLog(@"----%@", dict); 125 }]; 126 127 // 3.开始任务 128 [task resume]; 129 }
高级技术
1 - (NSURLSession *)session 2 { 3 if (!_session) { 4 // 获得session 5 NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration]; 6 self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 7 } 8 return _session; 9 } 10 11 - (void)viewDidLoad 12 { 13 [super viewDidLoad]; 14 // Do any additional setup after loading the view, typically from a nib. 15 16 } 17 18 - (IBAction)download:(UIButton *)sender { 19 // 按钮状态取反 20 sender.selected = !sender.isSelected; 21 22 if (self.task == nil) { // 开始(继续)下载 23 if (self.resumeData) { // 恢复 24 [self resume]; 25 } else { // 开始 26 [self start]; 27 } 28 } else { // 暂停 29 [self pause]; 30 } 31 } 32 33 /** 34 * 从零开始 35 */ 36 - (void)start 37 { 38 // 1.创建一个下载任务 39 NSURL *url = [NSURL URLWithString:@"http://192.168.15.172:8080/MJServer/resources/videos/minion_01.mp4"]; 40 self.task = [self.session downloadTaskWithURL:url]; 41 42 // 2.开始任务 43 [self.task resume]; 44 } 45 46 /** 47 * 恢复(继续) 48 */ 49 - (void)resume 50 { 51 // 传入上次暂停下载返回的数据,就可以恢复下载 52 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; 53 54 // 开始任务 55 [self.task resume]; 56 57 // 清空 58 self.resumeData = nil; 59 } 60 61 /** 62 * 暂停 63 */ 64 - (void)pause 65 { 66 __weak typeof(self) vc = self; 67 [self.task cancelByProducingResumeData:^(NSData *resumeData) { 68 // resumeData : 包含了继续下载的开始位置\下载的url 69 vc.resumeData = resumeData; 70 vc.task = nil; 71 }]; 72 } 73 74 #pragma mark - NSURLSessionDownloadDelegate 75 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 76 didFinishDownloadingToURL:(NSURL *)location 77 { 78 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 79 // response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致 80 NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; 81 82 // 将临时文件剪切或者复制Caches文件夹 83 NSFileManager *mgr = [NSFileManager defaultManager]; 84 85 // AtPath : 剪切前的文件路径 86 // ToPath : 剪切后的文件路径 87 [mgr moveItemAtPath:location.path toPath:file error:nil]; 88 } 89 90 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 91 didWriteData:(int64_t)bytesWritten 92 totalBytesWritten:(int64_t)totalBytesWritten 93 totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite 94 { 95 NSLog(@"获得下载进度--%@", [NSThread currentThread]); 96 // 获得下载进度 97 self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite; 98 } 99 100 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 101 didResumeAtOffset:(int64_t)fileOffset 102 expectedTotalBytes:(int64_t)expectedTotalBytes 103 { 104 105 } 106 107 //- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data 108 //{ 109 // 110 //} 111 // 112 //- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler 113 //{ 114 // 115 //}
iOS开发——网络编程OC篇&(十)NSURLConnection/NSSeccession
标签:
原文地址:http://www.cnblogs.com/iCocos/p/4550358.html