网络篇 - 02.NSURLConnection基本使用
2015-08-26 20:56
405 查看
0.前述
由于目前苹果在推出NSURLSession后更推荐我们使用它,而此前的NSURLConnection已经在最新的Xcode7上已经过期目前最流行的第三方框架AFNetworking也是基于NSURLConnection和NSURLSession的封装
为了更好的理解网络通信的内部实现原理,这里会对基本的NSURLConnection、NSURLSession到后续AFN进行探究,更方便我们理解和使用第三方框架,甚至自己搭建框架等等…
1.网络请求常用类
NSURL:请求地址NSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有
一个NSURL对象
请求方法、请求头、请求体
请求超时
NSMutableURLRequest:NSURLRequest的子类
NSURLConnection
负责发送请求,建立客户端和服务器的连接
发送数据给服务器,并收集来自服务器的响应数据
2.URL中的中文问题
若是URL中有中文如果是POST请求, 参数中可以有中文
如果是GET请求, URL中不能有中文
开发技巧: 无论是get/post, 都对URL进行一次转码
示例代码
// GET NSString *urlStr = @"http://120.25.226.186:32812/login?username=用户名&pwd=密码&type=JSON"; [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] // POST,由于POST的参数在请求体中,所以需要对请求体转码 // 1.获取URL NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"]; // 2.根据URL创建NSURLRequest NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.HTTPMethod = @"POST"; request.HTTPBody = [@"username=用户名&pwd=密码&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
2.NSURLConnection的使用步骤
创建一个NSURL对象,设置请求路径传入NSURL创建一个NSURLRequest对象,设置请求头和请求体
使用NSURLConnection发送请求
3.同步+GET请求
// 同步GET -(void)sendSync{ // 1.创建URL NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=zj&pwd=123&type=JSON"]; // 2.根据URL创建请求对象 // 默认情况下NSURLRequest会自动给我们设置好请求头 // request默认情况下就是GET请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 3.利用NSConnection发送请求(同步) /* 第一个参数: 需要请求的对象 第二个参数: 服务返回给我们的响应头信息 第三个参数: 错误信息 返回值: 服务器返回给我们的响应体(NSData类型) */ NSHTTPURLResponse *response = nil; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; // 输出响应体数据 NSLog(@"data = %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); // 输出响应数据大小,以及响应头内容 NSLog(@"%zd,%@",response.expectedContentLength,response.allHeaderFields); // response的真实类型 NSLog(@"%@",[response class]); }
4.异步+GET请求
// 异步GET -(void)sendAsync{ // 1.创建URL NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=zj&pwd=123&type=JSON"]; // 2.根据URL创建请求对象 // 默认情况下NSURLRequest会自动给我们设置好请求头 // request默认情况下就是GET请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 3.发送异步请求 /* 参数解释: 第一个参数:传入的请求对象 第二个参数:回调block的队列, 决定了block在哪个线程中执行 第三个参数:完成请求后的回调 方法没有返回值 */ [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { /* block参数解释 第一个参数:响应头 第二个参数:响应体 第三个参数:错误信息 */ NSLog(@"%@",[NSThread currentThread]); }]; }
5.异步+POST请求
// 异步POST -(void)sendPOST{ // 1.创建URL NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"]; // 2.根据URL创建请求对象 // request默认情况下就是GET请求,我们需要手动设置请求模式,同时POST请求需要设置请求体 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; // 设置请求模式 request.HTTPMethod = @"POST"; // 设置请求体,注意: 如果是给POST请求传递参数: 那么不需要写?号 request.HTTPBody = [@"username=zj&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding]; // 3.发送请求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); }]; }
6.监听请求的具体传输过程
发送请求设置代理的三种方法// 方法一:只要调用alloc/initWithRequest, 系统会自动发送请求 NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; // 方法二: // 参数解释:startImmediately,如果传递YES, 系统会自动发送请求; 如果传递NO, 系统不会自动发送请求(需要调用[conn start]方法) NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; // 方法三: NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
示例代码
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // 监听具体请求过程,需要设置代理 // 1.创建URL NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; // 2.根据URL创建请求对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 3.发送请求,并设置代理(三种方法) NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self]; } #pragma mark - NSURLConnectionDataDelegate /* 只要接收到服务器的响应就会调用 response:响应头 */ -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ // 获取服务器返回给我们的文件的总大小 NSLog(@"%zd", response.expectedContentLength); } /* 接收到服务器返回的数据时调用(该方法可能调用一次或多次) data: 服务器返回的数据(当前这一次传递给我们的, 并不是总数) */ -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // 这一次传输的数据 NSLog(@"%zd", data.length); } // 接收完成后调用 -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSLog(@"%s",__func__); } // 请求过程中发生错误后调用 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"%s",__func__); }
相关文章推荐
- 网络篇 - 01.网络编程概述
- 网络方面的面试题
- TCP/IP详解 卷I:协议 の校验和
- TCP/IP详解 卷I:协议 のUDP 用户数据包协议
- 计算机网络面试题2
- 计算机网络面试题1
- 常见HTTP错误代码大全
- http头需知
- HttpClient 4.3教程
- http Cache-Control: If-None-Match ETag/If-Modifed-Since Last-Modified
- BZOJ 1491 [NOI2007]社交网络
- Android之Http,Socket和Tcp/Ip
- HttpServletRequest常用获取URL的方法
- Http请求与响应
- HTTP返回代码 201 304 404 500等代表的含义
- Linux的PXE kickstart网络自动装机
- (三) HTTP/2的帧
- AngularJS中的$http.post与jQuery.post的区别
- 贝叶斯网络
- 【使用JSOUP实现网络爬虫】清理HTML-消除不受信任的html (来防止xss攻击)