iOS--NetWorking

ViewController.m#

//
//  ViewController.m
//  NetWorking

//

#import "ViewController.h"
#import "NewsModel.h"


#define   BASE_URL  @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"

#define URL_PORT1 @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define URL_PORT2 @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"

@interface ViewController ()<NSURLConnectionDataDelegate>


@property(nonatomic, strong)NSMutableArray *dataArray;

@property(nonatomic,strong)NSMutableData *tempData;//NSURLConnectionDataDelegate

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /*
     1、同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,
     
     2、异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行
     
     3、GET请求,将参数直接写在访问路径上。操作简单,不过容易被外界看到,安全性不高,地址最多255字节;
     
     4、POST请求,将参数放到body里面。POST请求操作相对复杂,需要将参数和地址分开,不过安全性高,参数放在body里面,不易被捕获。
     */
    
    //1.发送请求
         //url : = 网络协议(http://今后可能是https) + 文件路径? + 参数1 & 参数2 ....
    //2.接受响应
    //3.创建链接对象传输数据
    
    
    //xcode7之后若想要使用HTTP需要修改info.plist文件
//    NSAppTransportSecurity NSDictionary
//    
//    NSAllowsArbitraryLoads  BOOL  YES
    
}
#pragma mark------GET同步  POST同步 -----------------------------------------------
//1.
- (IBAction)GETaction1:(UIButton *)sender {
    NSLog(@"GET 同步");
    //1.创建URL对象(URL:(网址)统一资源定位符,额被称为网页地址,是因特网上标准的资源的地址)
    NSURL *url = [NSURL URLWithString:BASE_URL];
    //2.创建链接对象(request:请求,需要)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //2.1 创建请求方式(默认是get,这一步可以不写)
    [request setHTTPMethod:@"get"];
    //3.创建响应对象
    NSURLResponse *response = nil;
    //
    NSError *error = nil;
    //4.创建连接对象(同步)
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: &error];
    if (nil !=data) {
    //解析
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    self.dataArray = [NSMutableArray arrayWithCapacity:5];//开辟空间!!!!!!!!!!!!!!!
    for (NSDictionary *dic1 in dic[@"news"]) {
        NewsModel *newsModel = [NewsModel new];
        [newsModel setValuesForKeysWithDictionary:dic1];
        [_dataArray addObject:newsModel];
    }
                //数组检测
                for (NewsModel *newmodel in _dataArray) {
                    NSLog(@"%@",newmodel);
                }
            //    NSLog(@"%@",_dataArray);//此方法打出乱码,因为没遍历;用上边方法
  }
}
- (IBAction)POSTaction1:(UIButton *)sender {
    NSLog(@"POST 同步");
    //1.创建URL对象
    NSURL *url = [NSURL URLWithString:URL_PORT1];
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //2.1 创建请求方式(必须写)
    [request setHTTPMethod:@"post"];//默认请求方式是get
    //3.设置请求参数
    NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding ];
    [request setHTTPBody:tempData];
    //4.创建响应对象
    NSURLResponse *response = nil;
    NSError *error = nil;
    //5.创建连接对象
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    //6.
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//    NSLog(@"%@",dic);
    
    self.dataArray = [NSMutableArray arrayWithCapacity:5];
    for (NSDictionary *dic2 in dic[@"news"]) {
        NewsModel *newsmodel2 = [NewsModel new];
        [newsmodel2 setValuesForKeysWithDictionary:dic2];
        [_dataArray addObject:newsmodel2];
    }
    
    for (NewsModel *newamodel2 in _dataArray) {
        NSLog( @"%@",newamodel2);
    }
    
}
#pragma mark----- GET异步--BLOCK    POST异步__BLOCK --------------------------------------------
//GET异步----------
- (IBAction)GETaction2:(UIButton *)sender {
    NSLog(@"GET异步");
    //1.创建URl对象
    NSURL *url = [NSURL URLWithString:BASE_URL];
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //3.直接创建连接对象([NSOperationQueue mainQueue]主队列,多线程内容)
    __weak typeof (self)temp = self;
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
        NSLog(@"%@",dic);
    temp.dataArray = [NSMutableArray arrayWithCapacity:5];
        for (NSDictionary *dic2 in dic[@"news"]) {
            NewsModel *newsmodel2 = [NewsModel new];
            [newsmodel2 setValuesForKeysWithDictionary:dic2];
            [_dataArray addObject:newsmodel2];
        }
        
        
    }];
   for (NewsModel *newamodel2 in _dataArray) {
            NSLog( @"%@",newamodel2);
        }
    NSLog(@"------------------- ");
}
//POST异步------------
- (IBAction)POSTaction2:(UIButton *)sender {
    
    NSLog(@"POST异步");
    //1.创建URL对象
    NSURL *url = [NSURL URLWithString:URL_PORT1];
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    //2.1 创建请求方式(必须写)
    [request setHTTPMethod:@"post"];//默认请求方式是get
    //3.设置请求参数
    NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding ];
    [request setHTTPBody:tempData];
    //3.直接创建连接对象
    __weak typeof (self)temp = self;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        temp.dataArray =[NSMutableArray arrayWithCapacity:5];
        for (NSDictionary *dic2 in dic[@"news"]) {
            NewsModel *newsmodel2 = [NewsModel new];
            [newsmodel2 setValuesForKeysWithDictionary:dic2];
            [_dataArray addObject:newsmodel2];
        }
        
        

    }];
    
    for (NewsModel *newamodel2 in _dataArray) {
            NSLog( @"%@",newamodel2);
        }

}
- (IBAction)GETactiondaili:(UIButton *)sender {
    NSLog(@"GET 异步代理");
    
    //1.创建URl对象
    NSURL *url = [NSURL URLWithString:BASE_URL];
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //创建连接对象,并实现代理
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    //
    [connection start];
    
    
}
- (IBAction)POSTactiondaili:(UIButton *)sender {
    NSLog(@"POST 异步代理");
    //1.创建URl对象
    NSURL *url = [NSURL URLWithString:URL_PORT1];
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];


    [request setHTTPMethod:@"post"];//默认请求方式是get

    NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding ];
    [request setHTTPBody:tempData];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
    
    
}

#pragma mark -----NSURLConnectionDataDelegate-------
//接收到服务器的响应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
   //准备数据接收
    self.tempData = [NSMutableData data];

}
//接收到请求的数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
   //将每次新接收到的数据拼接到原有数据包的后面
    [_tempData appendData:data];
    
}
//加载完毕,开始解析
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_tempData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",dic);
//    
//    for (NSDictionary *dict in dic[@"news"]) {
//        NewsModel *new = [NewsModel new];
//        [new setValuesForKeysWithDictionary:dict];
//        [_dataArray addObject:new];
//    }
//    
//    for (NewsModel *new in _dataArray) {
//        NSLog(@"%@",new.title);
//    }
    self.dataArray = [NSMutableArray arrayWithCapacity:5];//开辟空间!!!!!!!!!!!!!!!
    for (NSDictionary *dic1 in dic[@"news"]) {
        NewsModel *newsModel = [NewsModel new];
        [newsModel setValuesForKeysWithDictionary:dic1];
        [_dataArray addObject:newsModel];
    }
    //数组检测
    for (NewsModel *newmodel in _dataArray) {
        NSLog(@"%@",newmodel);
    }

    
    
}

//打印失败信息
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"文件连接出现error:%@",error);
}



#pragma mark==========================--- 解析新方法 ---========================

- (IBAction)sessionGET:(UIButton *)sender {
    NSLog(@"seeeion---GET");
    
    //1.创建URl对象
    NSURL *url = [NSURL URLWithString:BASE_URL];
    //2.创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    //3.创建task(该方法内部做了处理,默认使用get,直接传递URL即可)
    NSURLSessionTask *task = [session dataTaskWithRequest:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //数据操作
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        
        self.dataArray = [NSMutableArray arrayWithCapacity:5];//开辟空间!!!!!!!!!!!!!!!
        for (NSDictionary *dic1 in dic[@"news"]) {
            NewsModel *newsModel = [NewsModel new];
            [newsModel setValuesForKeysWithDictionary:dic1];
            [_dataArray addObject:newsModel];
        }
        //数组检测
        for (NewsModel *newmodel in _dataArray) {
            NSLog(@"%@",newmodel);
        }
    }];
    //4.起动会话
    [task  resume];
}




- (IBAction)sessionPOST:(UIButton *)sender {
    NSLog(@"seeeion---POST");
    //1.创建URL对象
    NSURL *url = [NSURL URLWithString:BASE_URL];
    //2.创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //创建请求方式
    
    [request setHTTPBody:@"post"];
    
    NSData *tempData = [URL_PORT2 dataUsingEncoding:NSUTF8StringEncoding];
    
    [request setHTTPBody:tempData];
    //3.建立对话
    NSURLSession *session = [NSURLSession sharedSession];
    //session支持3种类型的任务:
                //1. NSURLSessionDataTask(加载数据)
                //2. NSURLSessionDownloadTask(下载)
                //3. NSURLSessionUploadTask(上传)
    
    NSLog(@"---%d",[[NSThread currentThread] isMainThread]);//关于多线程
    
     __weak typeof (self)temp = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       //解析
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        NSLog(@"%@",dic);
        NSLog(@"----------------------%d",[[NSThread currentThread] isMainThread]);
       
        //回到主线程(刷新数据)
        dispatch_async(dispatch_get_main_queue(), ^{
//            [temp.tableView reloadData];
        });
    
    }];
    
    //4. 启动任务
    [task  resume];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

//
//  NewsModel.h
//  NetWorking
//
//

#import <Foundation/Foundation.h>

@interface NewsModel : NSObject

@property (nonatomic, assign)NSInteger code;

@property (nonatomic, strong)NSString *cid;

@property (nonatomic, strong)NSString *cname;

@property (nonatomic, assign)NSInteger commentCount;

@property (nonatomic, strong)NSString *ID;

@property (nonatomic, strong)NSString *lastUpdateTime;

@property (nonatomic, strong)NSString *nswaUrl;

@property (nonatomic, strong)NSString *picUrl;

@property (nonatomic, assign)NSInteger rownum;

@property (nonatomic, strong)NSString *sequence;

@property (nonatomic, strong)NSString *summary;

@property (nonatomic, strong)NSString *title;

@property (nonatomic, strong)NSString *type;

@property (nonatomic, strong)NSString *typeld;

@end

NewsModel.m#

//
//  NewsModel.m
//  NetWorking
//

#import "NewsModel.h"

@implementation NewsModel

//容错处理
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
    if ([key isEqualToString:@"id"]) {
        _ID = value;
    }
}


- (NSString *)description
{
    return [NSString stringWithFormat:@"%@", _title];
}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容