移动互联网时代,网络通信已是手机终端必不可少的功能。我们的应用中也必不可少的使用了网络通信,增强客户端与服务器交互。这一篇提供了使用NSURLConnection实现http通信的方式。

NSURLConnection提供了异步请求、同步请求两种通信方式。

1、异步请求

iOS5.0 SDK NSURLConnection类新增的sendAsynchronousRequest:queue:completionHandler:方法,从而使iOS5支持两种异步请求方式。我们先从新增类开始。

1)sendAsynchronousRequest

iOS5.0开始支持sendAsynchronousReques方法,方法使用如下:

  1. - (void)httpAsynchronousRequest{
  2. NSURL *url = [NSURL URLWithString:@"http://url"];
  3. NSString *post=@"postData";
  4. NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  5. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  6. [request setHTTPMethod:@"POST"];
  7. [request setHTTPBody:postData];
  8. [request setTimeoutInterval:10.0];
  9. NSOperationQueue *queue = [[NSOperationQueue alloc]init];
  10. [NSURLConnection sendAsynchronousRequest:request
  11. queue:queue
  12. completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
  13. if (error) {
  14. NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);
  15. }else{
  16. NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
  17. NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  18. NSLog(@"HttpResponseCode:%d", responseCode);
  19. NSLog(@"HttpResponseBody %@",responseString);
  20. }
  21. }];
  22. }

sendAsynchronousReques可以很容易地使用NSURLRequest接收回调,完成http通信。

2)connectionWithRequest

iOS2.0就开始支持connectionWithRequest方法,使用如下:

  1. - (void)httpConnectionWithRequest{
  2. NSString *URLPath = [NSString stringWithFormat:@"http://url"];
  3. NSURL *URL = [NSURL URLWithString:URLPath];
  4. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  5. [NSURLConnection connectionWithRequest:request delegate:self];
  6. }
  7. - (void)connection:(NSURLConnection *)theConnection didReceiveResponse:(NSURLResponse *)response
  8. {
  9. NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
  10. NSLog(@"response length=%lld  statecode%d", [response expectedContentLength],responseCode);
  11. }
  12. // A delegate method called by the NSURLConnection as data arrives.  The
  13. // response data for a POST is only for useful for debugging purposes,
  14. // so we just drop it on the floor.
  15. - (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
  16. {
  17. if (mData == nil) {
  18. mData = [[NSMutableData alloc] initWithData:data];
  19. } else {
  20. [mData appendData:data];
  21. }
  22. NSLog(@"response connection");
  23. }
  24. // A delegate method called by the NSURLConnection if the connection fails.
  25. // We shut down the connection and display the failure.  Production quality code
  26. // would either display or log the actual error.
  27. - (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error
  28. {
  29. NSLog(@"response error%@", [error localizedFailureReason]);
  30. }
  31. // A delegate method called by the NSURLConnection when the connection has been
  32. // done successfully.  We shut down the connection with a nil status, which
  33. // causes the image to be displayed.
  34. - (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
  35. {
  36. NSString *responseString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
  37. NSLog(@"response body%@", responseString);
  38. }

connectionWithRequest需要delegate参数,通过一个delegate来做数据的下载以及Request的接受以及连接状态,此处delegate:self,所以需要本类实现一些方法,并且定义mData做数据的接受。

需要实现的方法:

1、获取返回状态、包头信息。

  1. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;

2、连接失败,包含失败。

  1. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

3、接收数据

  1. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;

4、数据接收完毕

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

connectionWithRequest使用起来比较繁琐,而iOS5.0之前用不支持sendAsynchronousRequest。有网友提出了AEURLConnection解决方案。

  1. 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、同步请求

同步请求数据方法如下:

  1. - (void)httpSynchronousRequest{
  2. NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
  3. NSURLResponse * response = nil;
  4. NSError * error = nil;
  5. NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
  6. returningResponse:&response
  7. error:&error];
  8. if (error == nil)
  9. {
  10. // 处理数据
  11. }
  12. }

同步请求数据会造成主线程阻塞,通常在请求大数据或网络不畅时不建议使用。

从上面的代码可以看出,不管同步请求还是异步请求,建立通信的步骤基本是一样的:

1、创建NSURL

2、创建Request对象

3、创建NSURLConnection连接。

NSURLConnection创建成功后,就创建了一个http连接。异步请求和同步请求的区别是:创建了异步请求,用户可以做其他的操作,请求会在另一个线程执行,通信结果及过程会在回调函数中执行。同步请求则不同,需要请求结束用户才能做其他的操作。

/**
* @author 张兴业
*  iOS入门群:83702688
*  android开发进阶群:241395671
*  我的新浪微博:@张兴业TBOW
*/
 
参考:
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE
http://codewithchris.com/tutorial-how-to-use-ios-nsurlconnection-by-example/
http://kelp.phate.org/2011/06/ios-stringwithcontentsofurlnsurlconnect.html
 
from:http://blog.csdn.net/xyz_lmn/article/details/8968182

【转】iOS学习笔记(八)——iOS网络通信http之NSURLConnection的更多相关文章

  1. iOS学习笔记(八)——iOS网络通信http之NSURLConnection

    转自:http://blog.csdn.net/xyz_lmn/article/details/8968182 移动互联网时代,网络通信已是手机终端必不可少的功能.我们的应用中也必不可少的使用了网络通 ...

  2. iOS学习笔记(四)——iOS应用程序生命周期

    开发应用程序都要了解其生命周期,开始接触android时也是从应用程序生命周期开始的,android的应用程序生命周期更多是其组件的生命周期,例如Activity.Service.今天我们接触一下iO ...

  3. iOS学习笔记:iOS核心动画中的常用类型

    CATransaction 当我们在自定义的图层上修改某些支持动画的属性时,系统会为该属性的修改自动产生动画.这种其实属于隐式动画.隐式动画要得益于CATransaction. 一个CATransac ...

  4. iOS学习笔记-精华整理

    iOS学习笔记总结整理 一.内存管理情况 1- autorelease,当用户的代码在持续运行时,自动释放池是不会被销毁的,这段时间内用户可以安全地使用自动释放的对象.当用户的代码运行告一段 落,开始 ...

  5. iOS学习笔记总结整理

    来源:http://mobile.51cto.com/iphone-386851_all.htm 学习IOS开发这对于一个初学者来说,是一件非常挠头的事情.其实学习IOS开发无外乎平时的积累与总结.下 ...

  6. iOS学习笔记——AutoLayout的约束

    iOS学习笔记——AutoLayout约束 之前在开发iOS app时一直以为苹果的布局是绝对布局,在IB中拖拉控件运行或者直接使用代码去调整控件都会发上一些不尽人意的结果,后来发现iOS在引入了Au ...

  7. IOS学习笔记25—HTTP操作之ASIHTTPRequest

    IOS学习笔记25—HTTP操作之ASIHTTPRequest 分类: iOS2012-08-12 10:04 7734人阅读 评论(3) 收藏 举报 iosios5网络wrapper框架新浪微博 A ...

  8. IOS学习笔记之关键词@dynamic

    IOS学习笔记之关键词@dynamic @dynamic这个关键词,通常是用不到的. 它与@synthesize的区别在于: 使用@synthesize编译器会确实的产生getter和setter方法 ...

  9. iOS学习笔记10-UIView动画

    上次学习了iOS学习笔记09-核心动画CoreAnimation,这次继续学习动画,上次使用的CoreAnimation很多人感觉使用起来很繁琐,有没有更加方便的动画效果实现呢?答案是有的,那就是UI ...

随机推荐

  1. 51nod1305(简单逻辑)

    题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1305 题意:中文题诶- 思路:1e5的数据直接暴力肯定是不行 ...

  2. 手写堆的dijkstra

    颓废.. #include <cstdio> #include <cstring> #include <algorithm> using namespace std ...

  3. CF70D Professor's task(动态凸包)

    题面 两种操作: 1 往点集S中添加一个点(x,y); 2 询问(x,y)是否在点集S的凸包中. 数据保证至少有一个2操作, 保证刚开始会给出三个1操作, 且这三个操作中的点不共线. 题解 动态凸包板 ...

  4. MCP|LQD|Data-independent acquisition improves quantitative cross-linking mass spectrometry (DIA方法可提升交联质谱定量分析)

    文献名:Data-independent acquisition improves quantitative cross-linking mass spectrometry (DIA方法可提升定量交联 ...

  5. 在mac上使用sublime text3搭建opencv3开发环境

    安装sublime text3 打开mac终端,安装brew 安装opencv3,终端输入下面的coomand: brew install opencv@3 注意:@3表示安装的版本,如果不加@3,那 ...

  6. 在 CentOS7 安装 ELK【转】

    ELK是一个成熟的日志系统,主要功能有收集.分析.检索,详细见 elastic官网. 本文主要介绍如何在CentOS7下安装最新版本的ELK,当然现在docker已经有完全配置成功的elk容器,安装配 ...

  7. 基于CentOS系统下的Oracle的安装

    背景 最近的数据库的实验课,要求利用虚拟机安装CentOS系统,并在此系统上安装Oracle_11g软件实现监听,在windows系统上安装SQL Developer软件作为客户端 ,从而可以在SQL ...

  8. ffmpeg文件生成m3u8文件及ts切片程序(一)

    ffmpeg文件生成m3u8文件及ts切片程序(一) 实现目标:输入本地文件,实现m3u8切片,功能点请看注释,注意:注释很重要. 参考: http://www.cnblogs.com/mystory ...

  9. Codeforces Round #375 (Div. 2) Polycarp at the Radio 优先队列模拟题 + 贪心

    http://codeforces.com/contest/723/problem/C 题目是给出一个序列 a[i]表示第i个歌曲是第a[i]个人演唱,现在选出前m个人,记b[j]表示第j个人演唱歌曲 ...

  10. JavaScript 获取 Url 上的参数(QueryString)值

    获取URL里面传的参数,在Js中不能像后台一样使用Request.QueryString来获取URL里面参数,下面介绍两种方式用来获取参数 方式一:使用split分隔来获取,这种方法考试了地址中包含了 ...