iOS_GET_网络请求

同步的 get 请求

#pragma mark - 同步的 get 请求
- (IBAction)GETSynButtonDidClicked:(UIButton *)sender {

    // 1、网址里面必须写 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、如果网址有汉字需要转换(没有汉字也可以写)
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    // 3、根据字符串创建 url(统一资源定位符)
    NSURL *url = [NSURL URLWithString:urlString];

    // 4、根据 url 创建 request 请求类的对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 5、开始去请求网络、数据(同步) 返回data
    NSData *receiveData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    // 6、系统自带json解析
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: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);
    }
}

异步的 get 请求

#pragma mark - 异步的 get 请求
- (IBAction)GETAsyButtonDidClicked:(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、开始去请求网络、数据(同步) 返回data
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        // 5、系统自带json解析
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data 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);
        }

    }];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值