IOS之数据请求

为方便区分, 现在viewDidLoad创建4个Button :GET 同步请求 , POST同步请求, GET异步请求,POSt异步请求

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    [self.view addSubview:button];

    button.frame = CGRectMake(40, 40, 80, 50);

    button.backgroundColor = [UIColor cyanColor];

    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside ];

    [button setTitle:@"get 同步" forState:UIControlStateNormal];

    

    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];

    [self.view addSubview:button1];

    button1.frame = CGRectMake(40, 100, 80, 50);

    button1.backgroundColor = [UIColor orangeColor];

    [button1 addTarget:self action:@selector(buttonAction1:) forControlEvents:UIControlEventTouchUpInside ];

    [button1 setTitle:@"post 同步" forState:UIControlStateNormal];

    

    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];

    [self.view addSubview:button2];

    button2.frame = CGRectMake(180, 40, 80, 50);

    button2.backgroundColor = [UIColor greenColor];

    [button2 addTarget:self action:@selector(buttonAction2:) forControlEvents:UIControlEventTouchUpInside ];

    [button2 setTitle:@"get 异步" forState:UIControlStateNormal];

    

    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];

    [self.view addSubview:button3];

    button3.frame = CGRectMake(180, 100, 80, 50);

    button3.backgroundColor = [UIColor greenColor];

    [button3 addTarget:self action:@selector(buttonAction3:) forControlEvents:UIControlEventTouchUpInside ];

    [button3 setTitle:@"post 异步" forState:UIControlStateNormal];


    

    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 180, 200, 150)];

    self.imageView.backgroundColor = [UIColor lightGrayColor];

    [self.view addSubview:self.imageView];



}



1.GET同步请求

- (void)buttonAction:(UIButton *)button

{

     NSLog(@"get 同步");

   // 网络请求地址

    NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=银行&region=大连&output=json&ak=6E823f587c95f0148c19993539b99295";

   

    // 对中文进行编码(因为网址有中文 , 所以要进行中文转码)

    NSString *urlStrEcode = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

   

    // 1.创建URL地址

    NSURL *url = [NSURL URLWithString:urlStrEcode];

    

    // 2.创建请求对象

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    

    // 创建服务器响应信息对象

    NSURLResponse *response = nil;

    

    // 创建错误信息对象

    NSError *error = nil;

    

    // 3.向服务器发送请求

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response  error:&error];

// 由于该网址请求下来的数据是字典,所以要用字典接收, 如果是数组,用数组接收, 字典或数组就是你要用的数据

    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSLog(@"dic = %@", dic);

    NSLog(@"response = %@ error = %@", response, error);

}


2.POST同步

- (void)buttonAction1:(UIButton *)button1

{

    NSLog(@"post 同步");

    NSString *str = @"http://mhjk.1391.com/comic/comicslist_v2";

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 设置请求方式为post

    [request setHTTPMethod:@"POST"];

    

    // 设置参数

    NSString *bodyStr = @"subject=5&pagesize=21&pageno=1";

    // 将参数转为data

    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];

    // 设置请求对象body

    [request setHTTPBody:bodyData];

    

    NSURLResponse *response = nil;

    NSError *error = nil;

   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    // NSLog(@"response = %@", response);

    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSLog(@"dic = %@", dic);

}


3.GET异步  (该请求方式,要用到四个代理方法, 所以要签订协议: NSURLConnectionDataDelegate)

- (void)buttonAction2:(UIButton *)button2

{

    NSString *str = @"http://img4.duitang.com/uploads/item/201207/28/20120728105310_jvAjW.thumb.600_0.jpeg";

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    

#pragma mark 设置异步请求代理

    [NSURLConnection connectionWithRequest:request delegate:self];

    

}


#pragma mark -- 收到服务器响应

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"response = %@", response);

    

    // 初始化data属性

    self.data = [NSMutableData data];

}


#pragma mark -- 接收数据

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    // 接收data对象

    [self.data appendData:data];

   

}


#pragma mark -- 数据请求完成(数据请求解析可写在此方法里)

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

  NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:self.data options:0 error:nil];

    NSLog(@"array %@", array);

    

    

}


#pragma mark -- 数据请求失败

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"数据请求失败  %@", error);

    

}


4.POST异步(此方法最常用, GET请求也可以用)

- (void)buttonAction3:(UIButton *)button3

{

    NSLog(@"post 异步");

    NSString *str = @"http://mhjk.1391.com/comic/comicslist_v2";

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    // 没有body体可不写

    NSString *bodyStr1 = [NSString stringWithFormat:@"{\"subject\":\"%@\",\"pagesize\":\"%@\",\"pageno\":\"%@\"}", @"5", @"3", @"0"];

    NSLog(@"%@", bodyStr1);


    // 将body转为NSData类型

    NSData *data = [bodyStr1 dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    

    

    // post 异步请求 block

    // 参数1.request对象

    // 参数2.多线程队列NSOperationQueue对象

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

#pragma mark -- 遇到block 一定是回调回来的参数就是你要的数据

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        NSLog(@"dic = %@", dic);

        

    }];

}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值