0919-网络 请求 数据解析(掌握get post请求 解析json等代码即可)

http://localhost:8080/MJServer/video

复习看的: NSURLConnection 发送请求   暂时没有用到AFN

基本http请求 GET:

- (IBAction)login {
    // 1.用户名
    NSString *usernameText = self.username.text;
    if (usernameText.length == 0) {
        [MBProgressHUD showError:@"请输入用户名"];
        return;
    }
    
    // 2.密码
    NSString *pwdText = self.pwd.text;
    if (pwdText.length == 0) {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    
    /**
     接口文档:定义描述服务器端的请求接口
     1> 请求路径URL:客户端应该请求哪个路径  
     * http://localhost:8080/MJServer/login
     
     2> 请求参数:客户端要发给服务器的数据
     * username - 用户名
     * pwd - 密码
     
     3> 请求结果:服务器会返回什么东西给客户端
     {"error":"用户名不存在"}
     {"error":"密码不正确"}
     {"success":"登录成功"}
     */
    
    // 3.发送用户名和密码给服务器(走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];
    }
}
View Code

GET 解析返回的json

- (IBAction)login {
    // 1.用户名
    NSString *usernameText = self.username.text;
    if (usernameText.length == 0) {
        [MBProgressHUD showError:@"请输入用户名"];
        return;
    }
    
    // 2.密码
    NSString *pwdText = self.pwd.text;
    if (pwdText.length == 0) {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    
    // 3.发送用户名和密码给服务器(走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---");
    
    // 发送一个同步请求(在主线程发送请求)
    // queue :存放completionHandler这个任务
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
     ^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // 这个block会在请求完毕的时候自动调用
        if (connectionError || data == nil) {
            [MBProgressHUD showError:@"请求失败"];
            return;
        }
        
        // 解析服务器返回的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];
        }
     }];
    
//    NSLog(@"end---");
}
View Code

播放器控制器modal  播放音乐+ SDWebImage +reloadData(videos数组里网络获取到数据后 刷新表格)

//  HMVideosViewController.m

#import "HMVideosViewController.h"
#import "MBProgressHUD+MJ.h"
#import "HMVideo.h"
#import "UIImageView+WebCache.h"
#import <MediaPlayer/MediaPlayer.h>

#define HMUrl(path) [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/MJServer/%@", path]]

@interface HMVideosViewController ()
@property (nonatomic, strong) NSMutableArray *videos;
@end

@implementation HMVideosViewController

- (NSMutableArray *)videos
{
    if (!_videos) {
        self.videos = [[NSMutableArray alloc] init];
    }
    return _videos;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    /**
     加载服务器最新的视频信息
     */
    
    // 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];
    }];
}

#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;
}

#pragma mark - 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.取出对应的视频模型
    HMVideo *video = self.videos[indexPath.row];
    
    // 2.创建系统自带的视频播放控制器
    NSURL *url = HMUrl(video.url);
    MPMoviePlayerViewController *playerVc = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    
    // 3.显示播放器
    [self presentViewController:playerVc animated:YES completion:nil];
}
@end
View Code

GDataXML josn解析

- (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数据
        
        // 加载整个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];
    }];
}
View Code

NSXMLParser  sax方式解析

- (NSMutableArray *)videos
{
    if (!_videos) {
        self.videos = [[NSMutableArray alloc] init];
    }
    return _videos;
}

- (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;
}
View Code

POST请求

- (IBAction)login {
    // 1.用户名
    NSString *usernameText = self.username.text;
    if (usernameText.length == 0) {
        [MBProgressHUD showError:@"请输入用户名"];
        return;
    }
    
    // 2.密码
    NSString *pwdText = self.pwd.text;
    if (pwdText.length == 0) {
        [MBProgressHUD showError:@"请输入密码"];
        return;
    }
    
    // 增加蒙板
    [MBProgressHUD showMessage:@"正在拼命登录中...."];
    
    // 3.发送用户名和密码给服务器(走HTTP协议)
    // 创建一个URL : 请求路径
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"];
    
    // 创建一个请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 5秒后算请求超时(默认60s超时)
    request.timeoutInterval = 15;
    
    request.HTTPMethod = @"POST";
    // 设置请求体
    NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", usernameText, pwdText];
    // NSString --> NSData
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    // 设置请求头信息
    [request setValue:@"iPhone 6" forHTTPHeaderField:@"User-Agent"];
    
    // 发送一个同步请求(在主线程发送请求)
    // queue :存放completionHandler这个任务
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:
     ^(NSURLResponse *response, NSData *data, NSError *connectionError) {
         // 隐藏蒙板
         [MBProgressHUD hideHUD];
         
//         NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
//         NSString *msg = [NSHTTPURLResponse localizedStringForStatusCode:resp.statusCode];
//         NSLog(@"%d %@ %@", resp.statusCode, msg, resp.allHeaderFields);
     
        // 这个block会在请求完毕的时候自动调用
        if (connectionError || data == nil) { // 一般请求超时就会来到这
            [MBProgressHUD showError:@"请求失败"];
            return;
        }
        
        // 解析服务器返回的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];
        }
     }];
}
View Code

GET请求www.baidu.com 无参数  打印返回结果

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 1.URL
    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
    
    // 2.请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    // 3.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", str);
    }];
}
View Code

发送JSON给服务器

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 1.URL
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/order"];
    
    // 2.请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 3.请求方法
    request.HTTPMethod = @"POST";
    
    // 4.设置请求体(请求参数)
    // 创建一个描述订单信息的JSON数据
    NSDictionary *orderInfo = @{
                                @"shop_id" : @"1243324",
                                @"shop_name" : @"啊哈哈哈",
                                @"user_id" : @"899"
                                };
    NSData *json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
    request.HTTPBody = json;
    
    // 5.设置请求头:这次请求体的数据不再是普通的参数,而是一个JSON数据
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    // 6.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil || connectionError) return;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSString *error = dict[@"error"];
        if (error) {
            [MBProgressHUD showError:error];
        } else {
            NSString *success = dict[@"success"];
            [MBProgressHUD showSuccess:success];
        }
    }];
    
}
View Code

 

POST提交多个参数  且参数同名而已  多值参数   服务器接收到$_array = $_POST['city']

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 1.URL
    NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/weather"];
    
    // 2.请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 3.请求方法
    request.HTTPMethod = @"POST";
    
    // 4.设置请求体(请求参数)
    NSMutableString *param = [NSMutableString string];
    [param appendString:@"place=beijing"];
    [param appendString:@"&place=tianjin"];
    [param appendString:@"&place=meizhou"];
    request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
    
    // 5.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data == nil || connectionError) return;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSString *error = dict[@"error"];
        if (error) {
            [MBProgressHUD showError:error];
        } else {
//            NSArray *weathers = dict[@"weathers"];
            NSLog(@"%@", dict);
        }
    }];
}
View Code

 

 

导入三方框架GDataXML  :

1、#import

2、导入动态库libxml2, 进入头文件看到提示  配置build setting -> Header Search Paths   ,build phases->Other linker flags   -lxm2

3、GdataXML里的.m文件有release 做非ARC配置  指定一下build phases ->GDataXMLNode.m -fno-objc-arc

--------------------------------

 

不用第三方的  用苹果自带的 性能最好   NSJSONSerialization

OC对象-》json二进制数据   不需要掌握 很少用到

---------

播放视频

 

#import <MediaPlayer/MediaPlayer.h>

MPMoviePlayerViewController *playerVc = [[MPMoviePlayerViewController alloc] initWithControllerURL:url];

[self presentViewController:playerVc animated:YES completion:nil];

 

#define HMUrl(path)     [NSURL URLWithString: [NSString stringWithFormat:@"http://localhost:8080/NJServer/%@",path]

NSURL *url = HMUrl(@"video");

 

解析小文件变成OC数据  GDataXML DOM方式   一次性加载   效率差一点       非ARC编写    需要导入GData框架 和 libxml2框架(因为GData里面有用到libxml2的东西)

解析大文件变成OC数据  NSXMLParser 效率高  一个个节点元素解析   事件驱动(SAX方式)

------

----------------------

使用GDataXML框架(与MBProgressHUD一样)

 

1、导入GDataXML文件夹

2、代码里 #import "GDataXMLNode.h"

3、因为GDataXMLNode.h包含了苹果动态库

所以需要导入 动态库 libxml2    并做2个配置

xcode -> 项目-》build settings->Header Search Paths添加一个路径 /usr/include/libxml2

xcode -> 项目-》build settings ->Other Linker Flags     -lxml2

4、因为GDataXMLNode.m文件里有release操作   且在arc环境下   所以需要再配置一下

xcode -> 项目-》build phases ->GDataXMLNode.m ->设置一下xcode->build phases->compile sources->GDataNode.m    -fno-objc-arc

 -----------

HTTP请求 NSMutableURLRequest(可变)和 NSURLRequest (不可变)

NSUrlRequest不能设置请求头 因为是不可不变的

----

请求行字符串转码

-------

--------

字典转NSData   交给请求体  (只有POST有请求体) 

--------------

如果不知道服务器返回data是什么就看看 是字典还是 数组  还是数组字典都包括

 

先输出 看看是什么   在确定格式 如NSDictionary *dict = [NSJSONSerialization JSONObject....]

-----------------

发送json给服务器

发送 son字符串的NSData需要设置 Content-Type  application/json   否则会被认为是普通参数

-------------

POST提交多值参数  参数名都一样  参数名称都一样而已   普通数据        服务器接收到的就是数组了$arr_place = $_POST['place'];

 

posted @ 2016-03-19 02:06  海龙王来了  阅读(155)  评论(0编辑  收藏  举报
友情链接:废钢破碎机  带式压滤机