网络编程-GET-同步和异步(delegate和block)

来源:互联网 发布:上班记录软件 编辑:程序博客网 时间:2024/05/17 21:59

HTTP:Hyper Text Transfer Protocol(超文本传输协议)适用于从万维网服务器传送超文本到本地浏览器的传输协议,HTTP是一个应用层协议,由响应和请求构成,是一个标准的客户端服务器模型。

数据模型

news.h文件:这些属性的数据类型要和后台文件中对应的数据类型一样,否则容易出错

@property(nonatomic,assign) NSInteger rowNum;
@property(nonatomic,strong) NSString *Id;
@property(nonatomic,strong) NSString *title;
@property(nonatomic,strong) NSString *type;
@property(nonatomic,strong) NSString *cid;
@property(nonatomic,strong) NSString *cname;
@property(nonatomic,strong) NSString *newsUrl;
@property(nonatomic,strong) NSString *typeId;
@property(nonatomic,assign) NSInteger sequence;
@property(nonatomic,assign) NSInteger attribute;
@property(nonatomic,strong) NSString *lastUpdateTime;
@property(nonatomic,strong) NSString *PUBLISHDATE;
@property(nonatomic,strong) NSString *picUrl;
@property(nonatomic,strong) NSString *summary;
@property(nonatomic,assign) NSInteger commentCount;
@property(nonatomic,strong) NSString *newsId;

news.m文件


-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    
    //占用系统关键字的key值需要重新指定映射
    if ([key isEqualToString:@"id"]) {
        
        _Id = value;
        
        NSLog(@"%@",key);
    }
}


//此方法适用于我们调试使用(debug模式下),检验model数据,直观的观察到model的值(默认打印的是地址)
- (NSString *)description
{
    return [NSString stringWithFormat:@"rowNum=%ld,Id=%@,title=%@,type=%@,cid=%@,cname=%@,newsUrl=%@,typeId=%@,sequence=%ld,attribute=%ld,lastUpdateTime=%@,PUBLISHDATE=%@,picUrl=%@,summary=%@,commentCount=%ld",_rowNum,_Id,_title,_type,_cid,_cname,_newsUrl,_typeId,_sequence,_attribute,_lastUpdateTime,_PUBLISHDATE,_picUrl,_summary ,_commentCount];
}

GET-同步请求方法

视图控制器的.m文件中

//GET请求时的url
#define GET_URL  @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20150921&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"

延展部分:

@interface ViewController ()<NSURLConnectionDataDelegate>

//创建一个接收数据的数组
@property(nonatomic,strong) NSMutableArray *dataArray;

//创建一个接收数据的对象
@property(nonatomic,strong) NSMutableData *allData;


@end


#pragma mark============GET 同步请求 ===============

- (IBAction)getsynchronizationAction:(UIButton *)sender {
    
    //1.创建URL
    NSURL *url = [[NSURL alloc] initWithString:GET_URL];
    
    //2.创建请求对象
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    
    //设置请求方式,默认是GET
    request.HTTPMethod = @"GET";
    
    //3.创建响应对象
    NSURLResponse *response = nil;
    
    //4.创建错误对象
    NSError *error = nil;
    
    //5.链接,请求数据,当请求数据成功后,response和error都有值了
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    //NSLog(@"%@",data);
    
 #pragma mark=======================================数据处理========================================
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
   //NSLog(@"%@",dict);
    
    NSArray *array = [dict objectForKey:@"news"];
    
    _dataArray = [NSMutableArray arrayWithCapacity:5];
    
   // NSLog(@"%@",array);
    
    for (NSDictionary *dic in array) {
        
        News *news = [[News alloc] init];
        
        [news setValuesForKeysWithDictionary:dic];
        
        [_dataArray addObject:news];
    }
    
    
    for (News *news in _dataArray) {
        NSLog(@"%@",news);
    }
    
}

Get-异步请求(Block)方法-------------------最常用

/#pragma mark================GET 异步请求(Block)====================
//- (IBAction)getAsynchronization:(id)sender
//{
//    
//    //创建请求对象
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:GET_URL]];
//    
//    //接收请求,并作出响应
//    [NSURLConnection sendAsynchronousRequest:request queue: [NSOperationQueue mainQueue]  completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError){
//        
//        //解析数据
//        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        
//        _dataArray = [NSMutableArray arrayWithCapacity:8];
//        
//        //封装model对象
//        for (NSDictionary *dic in dict[@"news"]) {
//            
//            News *news = [News new];
//            
//            [news setValuesForKeysWithDictionary:dic];
//            
//            [_dataArray addObject:news];
//        }
//        
//        //校验
//        for (News *news in _dataArray) {
//            NSLog(@"%@",news);
//        }
//        //注意:如果有tableView的话,要在数据请求完用[self.tableView reloadData]方法刷新
//    }];
 
   //注意:数据请求的时候,先执行block外的代码


GET-异步请求(delegate)方法

#pragma mark==================GET 异步请求-Delegate========================

- (IBAction)getAsynchronizationAction:(id)sender {
    
    //1.创建url对象
    NSURL *url = [[NSURL alloc] initWithString:GET_URL];
    
    //2.创建请求对象
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    
    //3.创建连接
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    //4.开始连接
    [connection start];
    
    
}


#pragma mark----------------------执行代理方法----------

//1.接收响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //创建接收数据对象
    _dataArray = [[NSMutableArray alloc] initWithCapacity:6];
    
    _allData = [[NSMutableData alloc] initWithCapacity:30];
    
}

//2.接收数据(反复执行)
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [_allData appendData:data];
    
}


//3.完成请求
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //解析数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_allData options:NSJSONReadingAllowFragments error:nil];
    NSArray *array = dict[@"news"];
    
    //处理数据
    for (NSDictionary *dic in array) {
        
        News *news = [[News alloc] init];
        [news setValuesForKeysWithDictionary:dic];
        
        [_dataArray addObject:news];
    }

    
    //校验
    for (News *news in _dataArray) {
        
        NSLog(@"%@",news);
        
    }
    
}



//4.错误处理
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"有误%@",error);
}
*/


0 0