iOS_网络请求_代理方式
2015-07-21 17:40
483 查看
#pragma mark - 网络请求代理方式(异步) - (IBAction)DelegateButtonDidClicked:(UIButton *)sender { // 1、拼接 urlString,网址里面必须写 http:// NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"; // 2、根据字符串创建 URL(统一资源定位符) NSURL *url = [NSURL URLWithString:urlString]; // 3、根据 url 创建 request 请求类的对象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 4、请求数据(代理回调方式)遵守代理 <NSURLConnectionDataDelegate> [NSURLConnection connectionWithRequest:request delegate:self]; }
代理方法
客户端收到服务器的响应
#pragma mark | 客户端收到服务器的响应 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // 只执行一次 // 初始化 receiveData 对象 self.receiveData = [NSMutableData data]; }
客户端收数据(并非一次性全部拿到)
#pragma mark | 客户端收数据(并非一次性全部拿到) - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 每次返回的都是新数据 // 拼接数据(请求一点 拼接一点) [self.receiveData appendData:data]; }
客户端接收数据完毕
#pragma mark | 客户端接收数据完毕 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // 解析数据 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.receiveData options:(NSJSONReadingMutableContainers) error:nil]; NSArray *array = dict[@"news"]; self.newsArray = [NSMutableArray array]; for (NSDictionary *smallDict in array) { NewsModal *modal = [[NewsModal alloc] init]; [modal setValuesForKeysWithDictionary:smallDict]; [self.newsArray addObject:modal]; } for (NewsModal *modal in self.newsArray) { NSLog(@"%@", modal.title); } }
网络请求失败
#pragma mark | 网络请求失败 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"%@", error); }
相关文章推荐
- Node.js 的 http 模块
- Java基础—socket--TCP-客户端服务器模式
- iOS_POST_网络请求
- GDB 单步调试 http://www.cppblog.com/baby-fly/archive/2010/07/27/121395.html
- iOS_GET_网络请求
- 该伙伴事务管理器已经禁止了它对远程/网络事务的支持
- Linux中TCP和UDP发送和接收缓冲区
- iOS开发中使用AFNetWorking进行https请求
- 网络字体/图标字体初体验
- 隧道和网络虚拟化:NVGRE vs VXLAN
- ./configure: error: the HTTP rewrite module requires the PCRE library
- linux脚本检测本机与指定IP段网络是否畅通
- httpd 命令解释
- PC-网络教程之宽带小型组网方案
- BAT-使用BAT方法判断网络启动EXE(快捷方式)
- Android 网络通信框架Volley简介(Google IO 2013)
- iOS:关于获取网络类型和运营商信息
- TCP/IP学习(四)TCP缓冲区大小及限制
- ERROR (ConnectionError): HTTPConnectionPool (Caused by <class 'socket.error'>: [Errno 111] Connecti
- 深入理解HTTP Session