【转】iOS学习笔记(八)——iOS网络通信http之NSURLConnection
移动互联网时代,网络通信已是手机终端必不可少的功能。我们的应用中也必不可少的使用了网络通信,增强客户端与服务器交互。这一篇提供了使用NSURLConnection实现http通信的方式。
NSURLConnection提供了异步请求、同步请求两种通信方式。
1、异步请求
iOS5.0 SDK NSURLConnection类新增的sendAsynchronousRequest:queue:completionHandler:方法,从而使iOS5支持两种异步请求方式。我们先从新增类开始。
1)sendAsynchronousRequest
iOS5.0开始支持sendAsynchronousReques方法,方法使用如下:
- - (void)httpAsynchronousRequest{
- NSURL *url = [NSURL URLWithString:@"http://url"];
- NSString *post=@"postData";
- NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
- [request setHTTPMethod:@"POST"];
- [request setHTTPBody:postData];
- [request setTimeoutInterval:10.0];
- NSOperationQueue *queue = [[NSOperationQueue alloc]init];
- [NSURLConnection sendAsynchronousRequest:request
- queue:queue
- completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
- if (error) {
- NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);
- }else{
- NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
- NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NSLog(@"HttpResponseCode:%d", responseCode);
- NSLog(@"HttpResponseBody %@",responseString);
- }
- }];
- }
sendAsynchronousReques可以很容易地使用NSURLRequest接收回调,完成http通信。
2)connectionWithRequest
iOS2.0就开始支持connectionWithRequest方法,使用如下:
- - (void)httpConnectionWithRequest{
- NSString *URLPath = [NSString stringWithFormat:@"http://url"];
- NSURL *URL = [NSURL URLWithString:URLPath];
- NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
- [NSURLConnection connectionWithRequest:request delegate:self];
- }
- - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response
- {
- NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
- NSLog(@"response length=%lld statecode%d", [response expectedContentLength],responseCode);
- }
- // A delegate method called by the NSURLConnection as data arrives. The
- // response data for a POST is only for useful for debugging purposes,
- // so we just drop it on the floor.
- - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
- {
- if (mData == nil) {
- mData = [[NSMutableData alloc] initWithData:data];
- } else {
- [mData appendData:data];
- }
- NSLog(@"response connection");
- }
- // A delegate method called by the NSURLConnection if the connection fails.
- // We shut down the connection and display the failure. Production quality code
- // would either display or log the actual error.
- - (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
- {
- NSLog(@"response error%@", [error localizedFailureReason]);
- }
- // A delegate method called by the NSURLConnection when the connection has been
- // done successfully. We shut down the connection with a nil status, which
- // causes the image to be displayed.
- - (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
- {
- NSString *responseString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
- NSLog(@"response body%@", responseString);
- }
connectionWithRequest需要delegate参数,通过一个delegate来做数据的下载以及Request的接受以及连接状态,此处delegate:self,所以需要本类实现一些方法,并且定义mData做数据的接受。
需要实现的方法:
1、获取返回状态、包头信息。
- - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
2、连接失败,包含失败。
- - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
3、接收数据
- - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
4、数据接收完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
connectionWithRequest使用起来比较繁琐,而iOS5.0之前用不支持sendAsynchronousRequest。有网友提出了AEURLConnection解决方案。
- AEURLConnection is a simple reimplementation of the API for use on iOS 4. Used properly, it is also guaranteed to be safe against The Deallocation Problem, a thorny threading issue that affects most other networking libraries.
2、同步请求
同步请求数据方法如下:
- - (void)httpSynchronousRequest{
- NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
- NSURLResponse * response = nil;
- NSError * error = nil;
- NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
- returningResponse:&response
- error:&error];
- if (error == nil)
- {
- // 处理数据
- }
- }
同步请求数据会造成主线程阻塞,通常在请求大数据或网络不畅时不建议使用。
从上面的代码可以看出,不管同步请求还是异步请求,建立通信的步骤基本是一样的:
1、创建NSURL
2、创建Request对象
3、创建NSURLConnection连接。
NSURLConnection创建成功后,就创建了一个http连接。异步请求和同步请求的区别是:创建了异步请求,用户可以做其他的操作,请求会在另一个线程执行,通信结果及过程会在回调函数中执行。同步请求则不同,需要请求结束用户才能做其他的操作。
【转】iOS学习笔记(八)——iOS网络通信http之NSURLConnection的更多相关文章
- iOS学习笔记(八)——iOS网络通信http之NSURLConnection
转自:http://blog.csdn.net/xyz_lmn/article/details/8968182 移动互联网时代,网络通信已是手机终端必不可少的功能.我们的应用中也必不可少的使用了网络通 ...
- iOS学习笔记(四)——iOS应用程序生命周期
开发应用程序都要了解其生命周期,开始接触android时也是从应用程序生命周期开始的,android的应用程序生命周期更多是其组件的生命周期,例如Activity.Service.今天我们接触一下iO ...
- iOS学习笔记:iOS核心动画中的常用类型
CATransaction 当我们在自定义的图层上修改某些支持动画的属性时,系统会为该属性的修改自动产生动画.这种其实属于隐式动画.隐式动画要得益于CATransaction. 一个CATransac ...
- iOS学习笔记-精华整理
iOS学习笔记总结整理 一.内存管理情况 1- autorelease,当用户的代码在持续运行时,自动释放池是不会被销毁的,这段时间内用户可以安全地使用自动释放的对象.当用户的代码运行告一段 落,开始 ...
- iOS学习笔记总结整理
来源:http://mobile.51cto.com/iphone-386851_all.htm 学习IOS开发这对于一个初学者来说,是一件非常挠头的事情.其实学习IOS开发无外乎平时的积累与总结.下 ...
- iOS学习笔记——AutoLayout的约束
iOS学习笔记——AutoLayout约束 之前在开发iOS app时一直以为苹果的布局是绝对布局,在IB中拖拉控件运行或者直接使用代码去调整控件都会发上一些不尽人意的结果,后来发现iOS在引入了Au ...
- IOS学习笔记25—HTTP操作之ASIHTTPRequest
IOS学习笔记25—HTTP操作之ASIHTTPRequest 分类: iOS2012-08-12 10:04 7734人阅读 评论(3) 收藏 举报 iosios5网络wrapper框架新浪微博 A ...
- IOS学习笔记之关键词@dynamic
IOS学习笔记之关键词@dynamic @dynamic这个关键词,通常是用不到的. 它与@synthesize的区别在于: 使用@synthesize编译器会确实的产生getter和setter方法 ...
- iOS学习笔记10-UIView动画
上次学习了iOS学习笔记09-核心动画CoreAnimation,这次继续学习动画,上次使用的CoreAnimation很多人感觉使用起来很繁琐,有没有更加方便的动画效果实现呢?答案是有的,那就是UI ...
随机推荐
- 大融合——LCT维护子树信息
题目 [题目描述] 小强要在 $N$ 个孤立的星球上建立起一套通信系统.这套通信系统就是连接 $N$ 个点的一个树.这个树的边是一条一条添加上去的.在某个时刻,一条边的负载就是它所在的当前能够联通的树 ...
- [Xcode 实际操作]三、视图控制器-(4)使用UINavigationController导航栏和工具栏
目录:[Swift]Xcode实际操作 本文将演示如何显示和隐藏导航视图的导航栏和工具栏 打开第一个视图控制器 import UIKit class FirstSubViewController: U ...
- [转][iOS Crash文件分析]-如何使用symbolicatecrash工具
上传一软件,被拒了,自己测试了n遍都未出现这个情况,今天用symbolicatecrash工具分析了一下苹果提供的Crash文件,最终查到是 - (void)mapView:(MKMapView *) ...
- 禁止tableview 像上滑动
tableView有一个bounces属性.默认YES,所以tableView上下用力拉都会有弹性滑动,如下设置可以禁止,但是这样的话上下弹性都没了 而经常的需求是上方不要弹性,下方要弹性,可以用监听 ...
- Spring对数据库的操作
Spring结合Hibernate HibernateTemplate http://www.jb51.net/article/41541.htm //////// ...
- java Bean的映射工具
数据层,业务逻辑层和表现层,每一层对应的应该是不一样的对象,所以就有个这么个java bean的映射工具 dozer.......................................... ...
- pat1049. Counting Ones (30)
1049. Counting Ones (30) 时间限制 10 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue The task ...
- Java排序算法(三)
Java排序算法(三) 三.Java排序算法总结 从这三组时间复杂度对比中,可以看出,堆排序和归并排序是不管在什么情况下发挥稳定的,快速排序好的时候表现如天才,坏情况下比较差强人意,甚至在等待排序个数 ...
- 如何在数据库中导入excel文件内的数据
如何在数据库中轻松导入excel格式的文件 1)打开sql server,找到要导入数据的数据库,右键>>任务>>导入数据 2)按照图示选择要导入的excel 3)选择导入到哪 ...
- 《Head First 设计模式》之适配器模式与外观模式
适配器模式(Adapter) 适配器(adapter-pattern):将一个类的接口,转换成客户期望的另一个接口.适配器让原来接口不兼容的类可以合作无间.两种形式: 对象适配器(组合) 类适配器(多 ...