UIday1604:get同步/异步 和 post同步/异步 编程实现
2015-09-17 17:26
155 查看
get同步/异步 和 post同步/异步 编程实现:
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> // 目的是用来拼接数据 @property(nonatomic,strong)NSMutableData * appendData; @property(nonatomic,strong)NSMutableDictionary * dataDict; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } // get同步 (一般不用同步请求) - (IBAction)getSync:(id)sender { // 1 准备URL(全球资源统一定位符) // http 协议 // 172.17.32.53IP地址或域名 // / 后面是路径 // ? 后面是参数(=前面是变量名,后面是传的值) NSString * urlStr = @"http://172.21.8.15/?userName=yan3&password=123"; NSURL * url = [NSURL URLWithString:urlStr]; // 2 创建请求对象 // NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];//第一种没有缓存策略 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30]; // 设置 // 如果不设置,这里默认是GET;但是post一定要设置。 [request setHTTPMethod:@"GET"]; // 3 创建响应对象 // 响应对象的目的是为了接收响应 NSURLResponse * response = nil; // 4 创建错误对象 // NSError * error = nil; // 5 发送请求,建立连接,接收(数据||响应||错误) NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; NSLog(@"data %@",data); NSLog(@"response %@",response); NSLog(@"error %@",error); } // get异步 - (IBAction)getAsyn:(id)sender { // 1 准备url NSString * urlStr = @"http://172.21.8.15/?userName=yan3&password=123"; NSURL * url = [NSURL URLWithString:urlStr]; // 2 创建请求对象 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; // 异步不需要创建响应和错误 // 3 发送请求,建立连接(代理的方式) NSURLConnection * conn = [NSURLConnection connectionWithRequest:request delegate:self]; // 4 启动 [conn start]; // 5 取消 // [conn cancel] } // post同步 (post不把问号后面的暴漏出来,问号也不显示) - (IBAction)postSync:(id)sender { // 1 准备url NSString * urlStr = @"http://172.21.8.15/"; NSURL * url = [NSURL URLWithString:urlStr]; // 2 准备请求对象 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; // 3 准备参数 NSString * paramStr = [NSString stringWithFormat:@"userName=yan3&password=123"]; // 将参数转换成NSData类型 NSData * paramData = [paramStr dataUsingEncoding:NSUTF8StringEncoding]; // 添加参数 [request setHTTPBody:paramData]; // 4 发送请求 建立连接 NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSLog(@"data : %@",data); // 5 解析 加判断 没有判断的话,如果data为空时,程序运行会崩溃 if (data != nil) { id temp = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"POST同步 %@",temp); }else{ NSLog(@"网络故障,没有数据"); } } // post异步 - (IBAction)postAsyn:(id)sender { // 1 准备URL NSString * urlStr = @"http://172.21.8.15/"; NSURL * url = [NSURL URLWithString:urlStr]; // 2 准备请求对象 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; // 3 准备参数 NSString * paramStr = [NSString stringWithFormat:@"userName=yan3&password=123"]; // 将参数转换为NSDdata类型 NSData * paramData = [paramStr dataUsingEncoding:NSUTF8StringEncoding]; // 添加参数 [request setHTTPBody:paramData]; // 4 发送请求,建立连接 (这步和POST同步不一样)(get异步请求也可以用这种方式) // queue跟多线程有关,是个操作队列 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSLog(@"%@",data); }]; // 5 解析 // NSString * receiveStr = [[NSString alloc]initWithData:request encoding:NSUTF8StringEncoding]; // NSLog(@"%@",receiveStr); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark --NSURLConnectionDataDelegate 协议方法 // 1 已经接收到响应 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ //马上开始传数据了 //response中包含了数据信息 //初始化 self.appendData = [NSMutableData data]; } // 2 接收到数据 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ //这个数据不是一次性传完,这个方法会走多次。 //要将data拼接起来 [self.appendData appendData:data]; } // 3 数据接收完毕 -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ //接收好的数据,处理。 //解析 //将接收到的数据转换为字符串类型的,然后输出 NSString * receiveStr = [[NSString alloc]initWithData:self.appendData encoding:NSUTF8StringEncoding]; NSLog(@"%@",receiveStr); } // 4 请求发生错误 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ NSLog(@"%@",[error localizedDescription]); } @end
相关文章推荐
- ubuntu 14.04 build SURFGPU
- HDU 5437 Alisha’s Party (Priority_queue)2015 ACM/ICPC Asia Regional Changchun Online
- iPhone开发之显示指定格式的文本自动改变UIlabel高度的自定义分类—— 方便好用
- Easyui DataGrid动态生成列
- Easyui DataGrid自定义视图和subGrid
- 异步图片加载Fresco v/s Universal Image Loader (UIL)
- Request中的getParameter和getAttribute的区别是什么?
- NGUI研究院之三种方式监听NGUI的事件方法(七)
- RegGetValue VS RegQueryValueEx
- duilib各种布局的作用,相对布局与绝对布局的的意义与用法
- request.getParameter() request.getAttribute()区别
- easyUI中点击datagrid列标题排序
- codeforces 450B Jzzhu and Sequences
- DelegatingRequestProcessor作用
- NGUI研究院之Sprite精灵与精灵动画的使用(二)
- 在最完整的搜索提示降史上的用户交互的研究——阅读《An Eye-tracking Study of User Interactions with Query Auto Completion》
- UISearchBar 修改背景颜色透明
- NGUI研究院之制作转圈的技能CD特效(八)
- Guid.NewGuid()
- LeetCode:Longest Consecutive Sequence