UI day 15 网络编程 GET请求 POST请求 同步连接 异步连接

本文详细介绍了iOS开发中GET和POST请求的实现方法,包括同步与异步请求的处理方式,以及如何处理请求过程中的数据解析和UI更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


                      GET请求 同步连接

#import "GETViewController.h"
#import “Business.h" 继承NSObject
{
@property (nonatomic,copy)NSString *name;
@property (nonatomic,copy)NSString *address;
@property (nonatomic,copy)NSString *telephone;
#import “Business.h”在.m中写

@implementation Business
- (
void)dealloc
{
   
self.name = nil;
   
self.address = nil;
   
self.telephone = nil;
    [
super dealloc];
   
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
   
}
@end
#import  “BusinessCell.h"  继承UITabelViewCell
@class Business;
@interface BusinessCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UILabel *nameLabel;
@property (retain, nonatomic) IBOutlet UILabel *telephoneLabel;
@property (retain, nonatomic) IBOutlet UILabel *addressLabel;
//提供一个接口给cell的子控件赋值
- (
void)assignValueByBusiness:(Business *)business;
#import "BusinessCell.h"
#import
"Business.h"
@implementation BusinessCell

- (
void)assignValueByBusiness:(Business *)business
{
   
self.nameLabel.text = business.name;
   
self.telephoneLabel.text = business.telephone;
   
self.addressLabel.text = business.address;
}

@interface GETViewController ()< NSURLConnectionDataDelegate >
@property ( nonatomic , retain ) NSMutableArray *dataSource;
@property ( nonatomic , retain ) NSMutableData *data; // 拼接多次请求下来的数据
@end

@implementation GETViewController
- (
void )dealloc
{
   
self . dataSource = nil ;
   
self . data = nil ;
    [
super dealloc ];
}
- (
NSMutableArray *)dataSource{
   
if ( _dataSource == nil ) {
        self.dataSource = [NSMutableArray arrayWithCapacity:0];    
    }
   
return [[_dataSource retain]autorelease];
}
// 同步请求 get  用storyboard添加的方法
- (IBAction)handleGetSyncRequst:(UIBarButtonItem *)sender
{
   
self.dataSource = nil;
//    NSLog(@"吃饱啦");
//    1.准备网址字符串
   
NSString *uilStr = @"http://api.map.baidu.com/place/v2/search?query=大保健&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
//    2.查看网址字符串中是否含有中文,有中文的话,要对uilStr进行转码
   
NSString *changeUilStr = [uilStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    3.创建NSURL对象,不仅能够存储本地的文件地址,也能存储网络地址
   
NSURL *url = [NSURL URLWithString:changeUilStr];
//    4.创建网络请求对象(NSURLRequest) 不可变的请求方法  默认的请求的方法就是get请求
//    NSMutableURLRequest可以设置网络的请求方式  是可变的请求方式
   
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    5.建立同步链接
//    5.1创建服务器响应对象
//    5.2创建请求失败错误信息存储对象
//    以上两个参数都是在方法的内部对其赋值
   
NSError *error = nil;
   
NSURLResponse *response = nil;
   
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   
NSLog(@"%@",data);
//    调用解析的方法
    [self parserData:data];  
}

//封装一个解析方法
- (
void)parserData:(NSData *)data
{
#pragma mark  解析数据的过程
    //    6.解析数据
   
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
   
//    NSLog(@"%@",dataDic);
   
//    7.取出resultskey值对应的数组
   
NSArray *array = dataDic[@"results"];
   
//    8.遍历数组中的字典,并使用给Model对象赋值
   
for (NSDictionary  *dic in array) {
       
        //9.创建数据模型对象
        Business *bus = [[Business alloc]init];
        //10.使用KVC赋值
        [bus setValuesForKeysWithDictionary:dic];
        //11.添加到存储所有商户信息的数组
        [self.dataSource addObject:bus];
        [bus
release];
    }
    //   12.更新UI界面
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
BusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aa" forIndexPath:indexPath];
//    取出数组中Model对象
   
Business *busine = self.dataSource[indexPath.row];
//    调用cell的赋值方法
    [cell assignValueByBusiness:busine];
    return cell;
}

                          GET请求   异步连接

// 异步 get 请求     用storyboard添加的方法
- (IBAction)handleGetAsyncRequst:(UIBarButtonItem *)sender {
  
   
self.dataSource = nil;
//1.创建网址字符串
   
NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=大保健&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
//    2.判断是否含有中文
   
NSString *changeUrl = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    3.创建NSURL对象,不仅能够存储本地的文件地址,也能存储网络地址
   
NSURL *url = [NSURL URLWithString:changeUrl];
//    4.创建网络请求对象(NSURLRequest) 不可变的请求方法  默认的请求的方法就是get请求
//    NSMutableURLRequest可以设置网络的请求方式  是可变的请求方式
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    5.创建异步网络链接方式
//    (NSOperationQueue *)队列类
//    [NSOperationQueue mainQueue]获取主队列
   
//    让当前的self对象处于引用状态
   
__block typeof (self) weakSelf = self;
    [
NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//        data就是请求下来的对象
//        response就是响应者
//        connectionError 就是存放链接是报错信息的对象
//        调用解析的方法
        [weakSelf
parserData:data];
    }];
  }  

                      GET请求  异步连接  使用代理方法

// 异步 get 请求  用storyboard添加的方法
- (IBAction)handleGetAsyncRequst:(UIBarButtonItem *)sender {
  
   
self.dataSource = nil;
//1.创建网址字符串
   
NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=大保健&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";
//    2.判断是否含有中文
   
NSString *changeUrl = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    3.创建NSURL对象,不仅能够存储本地的文件地址,也能存储网络地址
   
NSURL *url = [NSURL URLWithString:changeUrl];
//    4.创建网络请求对象(NSURLRequest) 不可变的请求方法  默认的请求的方法就是get请求
//    NSMutableURLRequest可以设置网络的请求方式  是可变的请求方式
   
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    5. 创建异步网络链接方式
//    代理完成异步解析
    [NSURLConnection connectionWithRequest:request delegate:self];

}
#pragma mark NSURLConnection 代理方法
//当接收到服务器响应的时候触发
- (
void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//    一旦接收到服务器的响应,就创建拼接的data对象
    self.data = [NSMutableData data];
}
//当接收到服务器数据的时候触发
//此方法有可能会触发多次,原因1:网络环境较差  原因2.请求的数据量比较大的时候,此时服务器会分多次把这个数据传输过来
- (
void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
   
//    拼接服务器传输的数据
    [
self.data appendData:data];
}
//当接收到服务器传输数据结束的时候触发
- (
void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//此时数据已经接受完毕,可以解析了
    [
self parserData:self.data];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

   
return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
BusinessCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aa" forIndexPath:indexPath];
//    取出数组中Model对象
   
Business *busine = self.dataSource[indexPath.row];
//    调用cell的赋值方法
    [cell assignValueByBusiness:busine];
    return cell;
}

                   POST请求    同步连接

用storyboard添加的方法
- (IBAction)handlePostSyncRequst:(UIBarButtonItem *)sender {
//    1.准备网站字符串
   
NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx/";
//    2.创建NSURL对象
   
NSURL *url = [NSURL URLWithString:urlStr];
//    3.创建网络请求对象
   
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    3.1配置请求方式
    request.
HTTPMethod = @"POST";
//    4.创建参数字符串
   
NSString *bodyDtring = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
//    4.1将字符串转换为NSData对象
   
NSData *data = [bodyDtring dataUsingEncoding:NSUTF8StringEncoding];
//    6.配置网络请求的参数
    request.
HTTPBody = data;
//5.创建网络链接
   
NSError *error = nil;
   
NSURLResponse *response = nil;
 
NSData  *data2 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
   
NSLog(@"%@",data2);
   
 }

                        POST请求    异步步连接

//POST 异步    用storyboard添加的方法
- (IBAction)handlePostAsyncRequst:(UIBarButtonItem *)sender {
//   1.准备网站字符串
   
NSString *urlStr = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx/";
//   2.创建NSURL对象
   
NSURL *url = [NSURL URLWithString:urlStr];
//   3.创建网络请求对象
   
NSMutableURLRequest *request = [NSMutableURLRequest  requestWithURL:url];
//   3.1创建请求方式
    request.
HTTPMethod = @"POST";
//    4.创建参数字符串
   
NSString *bodyTring = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
//    4.1将字符串转换为NSData
   
NSData *data = [bodyTring dataUsingEncoding:NSUTF8StringEncoding];
    request.
HTTPBody = data;
//    5.创建网络对象
[
NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
   
NSLog(@"%@",data);
    }];
   }

                          同步卡顿     UIViewController


#import "BigImageViewController.h"

@interface BigImageViewController ()
@property (retain, nonatomic) IBOutlet UIImageView *bigImageView;用storyboard添加的属性

@end

@implementation BigImageViewController 用storyboard添加方法
- (IBAction)handleKaDun:(UIButton *)sender {
  
//    1.准备网址字符串
   
NSString *urlStr = @"http://f1.topit.me/1/d2/8c/11663656284128cd21o.jpg";
//    2.初始化NSURL对象
   
NSURL *url = [NSURL URLWithString:urlStr];
//    3.创建请求对象
   
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    4.创建网络链接
//    4.1创建响应对象
   
NSURLResponse *response = nil;
   
NSError *error = nil;
 
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//    音乐数据  视频数据  图片数据不需要解析直接可以使用
   
self.bigImageView.image = [UIImage imageWithData:data];
   
   
   


        #############总结##################


同步请求和异步请求的差别:
 1.
同步请求,有主线程完成网络请求任务,在数据没有请求完成之前,用户的所有交互事件应用都无法处理,会造成一种卡顿现象,影响用户体验
 2.
异步请求,系统默认开辟子线程完成网络请求任务,主线程依然会处理用户的交互,此时不会出现卡顿现象,一旦开辟子线程就会消耗资源,此时就是那空间换时间
 























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值