ASI请求数据

来源:互联网 发布:c语言中求绝对值的代码 编辑:程序博客网 时间:2024/06/01 16:32

ASI请求数据有get请求和post请求

1 首先导入类库

2 引入包ASIHTTPRequest

3 在 .m文件中

UIButton *getButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [getButton setTitle:@"ASI get请求" forState:UIControlStateNormal];
    getButton.backgroundColor = [UIColor redColor];
    getButton.frame = CGRectMake(20, 100, 150, 40);
    [getButton addTarget:self action:@selector(asiGetRequest) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:getButton];
    
    
    
    UIButton *postButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [postButton setTitle:@"ASI post请求" forState:UIControlStateNormal];
    postButton.backgroundColor = [UIColor redColor];
    postButton.frame = CGRectMake(200, 100, 150, 40);
    [postButton addTarget:self action:@selector(asiPostRequest) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:postButton];


协议方法

#pragma mark --使用asi进行get请求 方法一
-(void)asiGetRequest
{
    //1.创建网络请求(GET)
        NSURL *url=[NSURL URLWithString:@"http://project.lanou3g.com/teacher/yihuiyun/lanouproject/activitylist.php"];
        self.request=[ASIHTTPRequest requestWithURL:url];
         //设置网络请求的延时为10秒钟
         self.request.timeOutSeconds=10;
   
         //2.设置代理
         self.request.delegate=self;
    
    
         //3.发送请求(异步请求)
         [self.request startAsynchronous];
}


#pragma mark --发送post请求
-(void)asiPostRequest
{
    
    
     //1.创建网络请求(POST)
         NSURL *url=[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
         ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    
         //2.添加请求参数(请求体中得参数)
         [request setPostValue:@"20131129" forKey:@"date"];
         [request setPostValue:@"5" forKey:@"startRecord"];
         [request setPostValue:@"5" forKey:@"len"];
         [request setPostValue:@"1234567890" forKey:@"udid"];
         [request setPostValue:@"Iphone" forKey:@"terminalType"];
         [request setPostValue:@"215" forKey:@"cid"];
    

          request.delegate = self;
          //3.发送请求
          [request startAsynchronous];
    
}


#pragma mark-  异步请求的代理方法
 //请求开始的时候调用
 -(void)requestStarted:(ASIHTTPRequest *)request
{
    self.myData = [NSMutableData data];
}
 //接收到服务器返回的数据时调用(数据量比较大的时候,这个方法会被调用多次,每次只能拿到部分数据)
 -(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data
{
    [self.myData appendData:data];
    
}
 //请求结束的时候调用(在该方法中拿到最终的数据)
 -(void)requestFinished:(ASIHTTPRequest *)request
{
    //将服务器返回的data型数据解析成大字典
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.myData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"dic = %@", dic);
    
}
//发送网络请求失败的时候调用
 -(void)requestFailed:(ASIHTTPRequest *)request
 {
     NSLog(@"请求失败");
 }







0 0
原创粉丝点击