UI 网络请求(同步GET,同步POST,异步GET,异步POST)具体操作

  1 #import "MainViewController.h"
  2
  3 @interface MainViewController ()<NSURLConnectionDataDelegate>
  4
  5 @property (nonatomic, retain)UIImageView *imageView;
  6
  7 @property (nonatomic, retain)NSMutableData *data;// 可变数据 Data 用于拼接每次接受来的数据块
  8 @end
  9
 10 @implementation MainViewController
 11
 12 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 13 {
 14     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 15     if (self) {
 16         // Custom initialization
 17     }
 18     return self;
 19 }
 20
 21 - (void)viewDidLoad
 22 {
 23     [super viewDidLoad];
 24     // Do any additional setup after loading the view.
 25     self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 20, 280, 280)];
 26     self.imageView.backgroundColor = [UIColor redColor];
 27     [self.view addSubview:self.imageView];
 28     [self.imageView release];
 29
 30     UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
 31     button1.frame = CGRectMake(20, 320, 120, 40);
 32     button1.backgroundColor = [UIColor brownColor];
 33     [button1 setTitle:@"同步 GET" forState:UIControlStateNormal];
 34     [button1 addTarget:self action:@selector(buttonClicked1:) forControlEvents:UIControlEventTouchUpInside];
 35     [self.view addSubview:button1];
 36
 37
 38     UIButton *button2 = [UIButton buttonWithType:UIButtonTypeSystem];
 39     button2.frame = CGRectMake(180, 320, 120, 40);
 40     button2.backgroundColor = [UIColor brownColor];
 41     [button2 setTitle:@"同步 POST" forState:UIControlStateNormal];
 42     [button2 addTarget:self action:@selector(buttonClicked2:) forControlEvents:UIControlEventTouchUpInside];
 43     [self.view addSubview:button2];
 44
 45
 46     UIButton *button3 = [UIButton buttonWithType:UIButtonTypeSystem];
 47     button3.frame = CGRectMake(20, 400, 120, 40);
 48     button3.backgroundColor = [UIColor brownColor];
 49     [button3 setTitle:@"异步 GET" forState:UIControlStateNormal];
 50     [button3 addTarget:self action:@selector(buttonClicked3:) forControlEvents:UIControlEventTouchUpInside];
 51     [self.view addSubview:button3];
 52
 53
 54     UIButton *button4 = [UIButton buttonWithType:UIButtonTypeSystem];
 55     button4.frame = CGRectMake(180, 400, 120, 40);
 56     button4.backgroundColor = [UIColor brownColor];
 57     [button4 setTitle:@"异步 POST" forState:UIControlStateNormal];
 58     [button4 addTarget:self action:@selector(buttonClicked4:) forControlEvents:UIControlEventTouchUpInside];
 59     [self.view addSubview:button4];
 60
 61 }
 62
 63 - (void)buttonClicked1:(UIButton *)button
 64 {
 65     // 同步GET
 66     // 1.拼接网络地址
 67     NSString *str  = @"http://cdn.gq.com.tw.s3-ap-northeast-1.amazonaws.com/userfiles/images_A1/6954/2011100658141857.jpg"
 68     ;
 69     // 2.将地址转化为URL对象
 70     NSURL *url = [NSURL URLWithString:str];
 71
 72     // 3. 创建一个请求(request)
 73     // 参数1: 请求地址(NSURL)
 74     // 参数2:给请求选择一个缓存策略
 75     // 参数3: 请求超时时间
 76     NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
 77     // 4. 给请求设置 请求方式
 78     [requset setHTTPMethod:@"GET"];
 79     // 5. 将请求发送给服务器
 80
 81     // 同步连接
 82     // 参数1:请求(request)
 83     // 参数2:响应信息
 84     // 参数3:错误信息
 85     // 同步连接的方法 会一直等待 数据完整接受之后才继续执行
 86     NSURLResponse *response = nil;
 87     NSError *error = nil;
 88     NSData *data = [NSURLConnection sendSynchronousRequest:requset returningResponse:&response error:&error];
 89
 90     //在这里获得的是完整的 data数据
 91     NSLog(@"服务器响应信息:%@", response);
 92
 93     // 使用NSData数据
 94     UIImage *image = [UIImage imageWithData:data];
 95     self.imageView.image = image;
 96     NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES));
 97
 98 }
 99 -(void)dealloc
100 {
101     [_data release];
102     [_imageView release];
103     [super dealloc];
104 }
105 - (void)buttonClicked2:(UIButton *)button
106 {
107     // 同步POST
108     NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
109     NSURL *url = [NSURL URLWithString:str];
110
111     // 创建请求
112     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
113     // 设置请求方式
114     [request setHTTPMethod:@"POST"];
115
116     // 产生一个body
117     NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
118     NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
119
120     // 设置post请求 附带的数据
121     [request setHTTPBody:data];
122
123     // 同步连接 获取内容
124     NSURLResponse *response = nil;
125     NSData *dataBack = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
126     NSLog(@"%@", response);
127
128     // 测试返回数据内容
129     NSString *result = [[NSString alloc] initWithData:dataBack encoding:NSUTF8StringEncoding];
130     NSLog(@"%@", result);
131
132 }
133
134 - (void)buttonClicked3:(UIButton *)button
135 {
136     // 异步
137     // 1. 产生请求
138     NSString *str = @"http://pic13.nipic.com/20110313/2686941_211532129160_2.jpg";
139     NSURL *url = [NSURL URLWithString:str];
140
141     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
142
143     [request setHTTPMethod:@"GET"];
144
145     // 2.建立连接
146     // 异步联接 不会卡死界面
147     // 参数1:设定好的请求
148     // 参数2:设定网络请求的代理人
149     [NSURLConnection connectionWithRequest:request delegate:self];
150
151
152 }
153 // 当收到服务器的响应信息 的时候 调用
154 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
155 {
156     // 当每次需要接受新的数据的时候 初始化data属性
157     NSLog(@"%s", __FUNCTION__);
158     self.data = [NSMutableData data];
159 }
160 // 当收到服务器发送来的 data数据块 的时候 调用
161 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
162 {
163     NSLog(@"%s", __FUNCTION__);
164     [self.data appendData:data];
165 }
166 // 当数据接受完毕 的时候 调用
167 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
168 {
169     // 调用这个方法 说明 self.data属性已经是一个完整的数据
170     NSLog(@"%s", __FUNCTION__);
171     UIImage *image = [UIImage imageWithData:self.data];
172     self.imageView.image = image;
173 }
174 - (void)buttonClicked4:(UIButton *)button
175 {
176     // 异步POST
177
178     NSString *str = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
179     NSURL *url = [NSURL URLWithString:str];
180
181     // 创建请求
182     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
183     // 设置请求方式
184     [request setHTTPMethod:@"POST"];
185
186     // 设置body
187     NSString *bodyStr = @"date=20131129&startRecord=1&len=30&udid=1234567890&terminalType=Iphone&cid=213";
188     NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
189
190     // 设置post请求 附带的数据
191     [request setHTTPBody:data];
192
193
194
195     // 2. 连接
196     // block 基础上的异步连接
197
198
199     // 参数1:请求
200     // 参数2:返回主线程
201     // 参数3:
202     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
203         // 当异步联接完毕 而且 请求但完整的数据(参数data)之后 才执行这个块的内容
204
205         // 在这个块中 写处理数据的代码 (解析/转化为image/音频/视频)
206         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
207         NSLog(@"%@", dic);
208     }];
209
210 }  
时间: 2024-08-07 01:06:39

UI 网络请求(同步GET,同步POST,异步GET,异步POST)具体操作的相关文章

网络请求数据(同步GET,异步GET)

////GET:将请求所需要传的参数,直接封装到URL中,缺点:1.不安全  2.url长度有限制,如果参数较多,会封装失败,导致无法请求 //POST:包含基础的url以及参数体,也就是说,参数跟url是分开的,比较安全且不用顾虑url的长度 //同步:当执行某个操作时,只有当其完全执行结束,才回去执行下面的操作,缺点:如果遇到耗时操作,会比较卡//异步:多个任务同时执行 #import "ViewController.h" #define BaseUrl @"http:/

网络请求数据(同步POST,异步POST)

//同步POST -(void)synPost{    //获取URL接口,不含参数    NSString *str = @"http://www.haninfo.cc:2060/Login/LoginData.asmx/Login";    //转码---拼接方法,为避免参数是汉字时,打印结果不显示汉字    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    NSURL *u

网络请求 get post

1.新建一个网络请求工具类,负责整个项目中所有的Http网络请求 提示:同步请求会卡住线程,发送网络请求应该使用异步请求(这意味着类方法不能有返回值) 2.工具类的实现 YYHttpTool.h文件 复制代码 1 // 2 // YYHttpTool.h 3 //网络请求工具类,负责整个项目中所有的Http网络请求 4 5 #import 6 7 @interface YYHttpTool : NSObject 8 /** 9 * 发送一个GET请求 10 * 11 * @param url 请

iOS开发项目篇—35封装网络请求

iOS开发项目篇—35封装网络请求 一.简单说明 1.分析项目对网路请求(AFN框架)的依赖 项目中,多个控制器都使用了AFN框架发送网络请求,如果AFN2.0存在重大BUg,或者是升级至3.0版本,那么对于整个项目都是及其危险的,所有用到AFN的地方都需要做出相应的修改. 另外,如果现在要求不再使用AFN框架,而是使用一个新的框架,那么有关AFN的依赖所关联的所有代码都需要重新来过. 如果把afn这个第三方框架从项目中删除的话,那么项目就相当于作废了,这就是项目对第三方框架的强依赖的体现. 说

IOS网络请求(同步GET,同步POST,异步GET,异步POST)

1.     同步GET请求     //第一步,创建URL     NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];          //第二步,通过URL创建网络请求     NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProt

【Java&amp;Android开源库代码剖析】のandroid-async-http(如何设计一个优雅的Android网络请求框架,同时支持同步和异步请求)开篇

在<[Java&Android开源库代码剖析]のandroid-smart-image-view>一文中我们提到了android-async-http这个开源库,本文正式开篇来详细介绍这个库的实现,同时结合源码探讨如何设计一个优雅的Android网络请求框架.做过一段时间Android开发的同学应该对这个库不陌生,因为它对Apache的HttpClient API的封装使得开发者可以简洁优雅的实现网络请求和响应,并且同时支持同步和异步请求. 网络请求框架一般至少需要具备如下几个组件:1

使用ab.exe监测100个并发/100次请求情况下同步/异步访问数据库的性能差异

ab.exe介绍 ab.exe是apache server的一个组件,用于监测并发请求,并显示监测数据 具体使用及下载地址请参考:http://www.cnblogs.com/gossip/p/4398784.html 本文的目的 通过webapi接口模拟100个并发请求下,同步和异步访问数据库的性能差异 创建数据库及数据 --创建表结构 CREATE TABLE dbo.[Cars] ( Id INT IDENTITY(1000,1) NOT NULL, Model NVARCHAR(50) 

iOS 网络与多线程--4.同步Post方式的网络请求

通过Post请求方式,同步获取网络数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据 在ViewController.m文件内的viewDidLoad函数添加一下测试代码 1 - (void)viewDidLoad { 2 [super viewDidLoad]; 3 // Do any additional setup after loading the view, typically from a nib. 4 5 // 1.建立一个网址对象,指定请求数据的网址 6 NSURL

AJAX请求详解 同步异步 GET和POST

AJAX请求详解 同步异步 GET和POST 上一篇博文(http://www.cnblogs.com/mengdd/p/4191941.html)介绍了AJAX的概念和基本使用,附有一个小例子,下面基于这个例子做一些探讨. 同步和异步 在准备请求的时候,我们给open方法里传入了几个参数,其中第三个参数为true时,表示是异步请求: //1. prepare request xmlHttpRequest.open("GET", "AjaxServlet", tru