一、发送用户名和密码给服务器(走HTTP协议)

// 创建一个URL : 请求路径
    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/MJServer/login?username=%@&pwd=%@",usernameText, pwdText];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 创建一个请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSLog(@"begin---");
    
    // 发送一个同步请求(在主线程发送请求)
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    // 解析服务器返回的JSON数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    NSString *error = dict[@"error"];
    if (error) {
        // {"error":"用户名不存在"}
        // {"error":"密码不正确"}
        [MBProgressHUD showError:error];
    } else {
        // {"success":"登录成功"}
        NSString *success = dict[@"success"];
        [MBProgressHUD showSuccess:success];
    }

二、加载服务器最新的视频信息json
    // 1.创建URL
    NSURL *url = HMUrl(@"video");
    
    // 2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 3.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
            return;
        }
        
        // 解析JSON数据
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSArray *videoArray = dict[@"videos"];
        for (NSDictionary *videoDict in videoArray) {
            HMVideo *video = [HMVideo videoWithDict:videoDict];
            [self.videos addObject:video];
        }
        
        // 刷新表格
        [self.tableView reloadData];
    }];

三、 加载服务器最新的视频信息XML

// 1.创建URL
    NSURL *url = HMUrl(@"video?type=XML");
    
    // 2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 3.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
            return;
        }
        
        // 解析XML数据
        
        // 加载整个XML数据
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil];
        
        // 获得文档的根元素 -- videos元素
        GDataXMLElement *root = doc.rootElement;
        
        // 获得根元素里面的所有video元素
        NSArray *elements = [root elementsForName:@"video"];
        
        // 遍历所有的video元素
        for (GDataXMLElement *videoElement in elements) {
            HMVideo *video = [[HMVideo alloc] init];
            
            // 取出元素的属性
            video.id = [videoElement attributeForName:@"id"].stringValue.intValue;
            video.length = [videoElement attributeForName:@"length"].stringValue.intValue;
            video.name = [videoElement attributeForName:@"name"].stringValue;
            video.image = [videoElement attributeForName:@"image"].stringValue;
            video.url = [videoElement attributeForName:@"url"].stringValue;
            
            // 添加到数组中
            [self.videos addObject:video];
        }
        
        // 刷新表格
        [self.tableView reloadData];
    }];

四、XML

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    /**
     加载服务器最新的视频信息
     */
    
    // 1.创建URL
    NSURL *url = HMUrl(@"video?type=XML");
    
    // 2.创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 3.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"网络繁忙,请稍后再试!"];
            return;
        }
        
        // 解析XML数据
        
        // 1.创建XML解析器 -- SAX -- 逐个元素往下解析
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
        
        // 2.设置代理
        parser.delegate = self;
        
        // 3.开始解析(同步执行)
        [parser parse];
        
        // 4.刷新表格
        [self.tableView reloadData];
    }];
}

#pragma mark - NSXMLParser的代理方法
/**
 *  解析到文档的开头时会调用
 */
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//    NSLog(@"parserDidStartDocument----");
}

/**
 *  解析到一个元素的开始就会调用
 *
 *  @param elementName   元素名称
 *  @param attributeDict 属性字典
 */
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if ([@"videos" isEqualToString:elementName]) return;
    
    HMVideo *video = [HMVideo videoWithDict:attributeDict];
    [self.videos addObject:video];
}

/**
 *  解析到一个元素的结束就会调用
 *
 *  @param elementName   元素名称
 */
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
//    NSLog(@"didEndElement----%@", elementName);
}

/**
 *  解析到文档的结尾时会调用(解析结束)
 */
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
//    NSLog(@"parserDidEndDocument----");
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videos.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"video";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    HMVideo *video = self.videos[indexPath.row];
    
    cell.textLabel.text = video.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"时长 : %d 分钟", video.length];
    
    // 显示视频截图
    NSURL *url = HMUrl(video.image);
    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placehoder"]];
    
    return cell;
}

 

ios 解析json,xml的更多相关文章

  1. ios之json,xml解析

    JSON解析步骤: 1.获取json文件路径 NSString*path = [[NSBundle mainBundle] pathForResource:@"Teacher"of ...

  2. IOS 解析Json数据(NSJSONSerialization)

    ● 什么是JSON ● JSON是一种轻量级的数据格式,一般用于数据交互 ● 服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除 外) ● JSON的格式很像OC中的字典和数组 ...

  3. (转)解析json xml

    JSON数据 {"videos":[{"id":1,"image":"resources/images/minion_01.png ...

  4. iOS解析JSON字符串报错Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence around character 586."

    将服务器返回的JSON string转化成字典时报错: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid escape sequence ...

  5. IOS 解析JSON

    - (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, t ...

  6. iOS 解析json串

    NSString *json = @"[{\"name\":\"a1\",\"items\":[{\"x1\" ...

  7. 玩转iOS开发 - JSON 和 Xml 数据解析

    前言 Json 和xml是网络开发中经常使用的数据格式,JSON轻量级.xml相对较复杂.所以如今用JSON的比例很大.基本上从server获取的返回数据都是JSON格式的,作为iOS开发人员,解析J ...

  8. ios 中使用SBJson拼接和解析json

    1.ios解析json 使用开源json包,项目地址:      http://stig.github.com/json-framework/ NSData * responseData = [res ...

  9. iOS网络-02-数据解析(JSON与XML)

    数据交互格式 服务器返回给用户的数据,通常是以下两种方式: JSON XML JSON 一种轻量级的数据数据格式,体积比XML小,是服务器返回给移动端通常采用的格式 用使用JSON文件中的数据,需要对 ...

随机推荐

  1. Java中字符串相等与大小比较

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html 内部邀请码:C8E245J (不写邀请码,没有现金送) 国 ...

  2. 【不积跬步,无以致千里】VIM查找替换归纳总结zz

    http://spaces.msn.com/dingy/blog/cns!2F24B9E66A542581!327.entry VIM中常用的替换模式总结. 1,简单替换表达式 替换命令可以在全文中用 ...

  3. 处理get中的中文乱码情况

    1 最基本的乱码问题.这个乱码问题是最简单的乱码问题.一般新会出现.就是页面编码不一致导致的乱码.<%@ page language="java" pageEncoding= ...

  4. C#用天气预报的WebServices

    后台代码: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { WeatherWS ws = new W ...

  5. Android 进阶学习:事件分发机制全然解析,带你从源代码的角度彻底理解(上)

    http://blog.csdn.net/guolin_blog/article/details/9097463 事实上我一直准备写一篇关于Android事件分发机制的文章,从我的第一篇博客開始,就零 ...

  6. MySQL Router 测试使用 转

    MySQL Router 测试使用 . 特性 MySQL Router 并没有包括一些特别新的特性, 总体上看中规中矩, 不过 first-available 和插件两个特性挺有意思, 后续会进行讲解 ...

  7. SQL Server XML Path[转]

    FOR XML PATH 有的人可能知道有的人可能不知道,其实它就是将查询结果集以XML形式展现,有了它我们可以简化我们的查询语句实现一些以前可能需要借助函数活存储过程来完成的工作.那么以一个实例为主 ...

  8. cocos2dx-3.2 环境配置

    一.软件 1)VS2012(C++11特性在VS2012以上可以使用) 2)Cocos2d-x官网源码 3)JDK 4)NDK(3.2要用r9d版本,用了android-ndk-r8e报错了) 5)A ...

  9. python 实现接口测试

    接口的类型有很多,但是我们经常遇见经常用的就get和post两种.这两种有什么区别呢?个人理解主要是表现在安全性方面. Python代码POST任意的HTTP数据以及使用Cookie的方法,有需要的朋 ...

  10. 小白日记30:kali渗透测试之Web渗透-扫描工具-Skipfish

    WEB渗透-skipfish Skipfish是一个命令行模式,以C语言编写的积极的Web应用程序的安全性侦察工具,没有代理模式. 它准备了一个互动为目标的网站的站点地图进行一个递归爬网和基于字典的探 ...