ios http网络请求

ios 7.0及之前版本使用NSURLConnection,7.0之后版本使用NSURLSession,本文给出两个组件的get和post方法


- (IBAction)netRequest:(id)sender {
  
    //self.nsURLConnectionGet;
    //self.nsURLConnectionPost;
    
//    self.nsUrlSessionGet;
      
    self.nsUrlSessionPost;
    
}
//NSURLSession get请求 ios7.0之后版本使用NSURLConnection
-(void)nsUrlSessionGet{
    NSURL *nsUrl=[NSURL URLWithString:@"https://www.baidu.com"];
    [[[NSURLSession sharedSession]dataTaskWithURL:nsUrl completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        id json=[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
//        NSLog(@"NSURLSession dataTask返回%@",json);
        
        NSString *string=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"NSURLSession dataTask get,返回data=%@",string);
    }] resume];
}
//NSURLSession带参post请求 ios7.0之后版本使用NSURLConnection
-(void)nsUrlSessionPost{
    // 1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];

    // 2.创建可变请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
    // 3.修改请求方法,POST必须大写
    request.HTTPMethod = @"POST";

    // request.HTTPMethod = @"HEAD";只请求页面的首部。

    // 可以设置请求头的一些属性,比如请求超时时间
    request.timeoutInterval = 10;

    // 设置请求头User-Agent  注意:key一定要一致(用于传递数据给后台)
    [request setValue:@"ios 16.2" forHTTPHeaderField:@"User-Agent"];
        
    // 可用于断点续传
    // [request setValue:[NSString stringWithFormat:@"bytes=%zd-", self.currentSize] forHTTPHeaderField:@"Range"];

    // 4.设置请求体信息,字符串--->NSData
    request.HTTPBody = [@"username=gzp&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
    
    [[[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        id json=[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
//        NSLog(@"NSURLSession dataTask返回%@",json);
        
        NSString *string=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"NSURLSession dataTask post,返回data=%@",string);
    }] resume];
}

//触摸屏幕,触发事件
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    self.nsUrlSessionGet;
}

//NSURLConnection简单get请求  ios7.0及之前版本使用NSURLConnection
-(void) nsURLConnectionGet {
    
   
    NSURL *nsUrl=[NSURL URLWithString:@"https://www.baidu.com"];
    NSURLRequest *nsUrlRequest=[NSURLRequest requestWithURL:nsUrl];
    [NSURLConnection sendAsynchronousRequest:nsUrlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(!connectionError){
            NSLog(@"response code %@",response.URL);
            NSString *string=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"简单get请求,返回data=%@",string);
        }else
        {
            NSLog(@"链接错误%@",connectionError);
        }
    }];
}



//NSURLConnection带参post请求 ios7.0及之前版本使用NSURLConnection
-(void) nsURLConnectionPost {
    /**
     * ios 7.0及以前版本使用NSURLConnection
     */
    // 1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];

    // 2.创建可变请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        
    // 3.修改请求方法,POST必须大写
    request.HTTPMethod = @"POST";

    // request.HTTPMethod = @"HEAD";只请求页面的首部。

    // 可以设置请求头的一些属性,比如请求超时时间
    request.timeoutInterval = 10;

    // 设置请求头User-Agent  注意:key一定要一致(用于传递数据给后台)
    [request setValue:@"ios 10.1" forHTTPHeaderField:@"User-Agent"];
        
    // 可用于断点续传
    // [request setValue:[NSString stringWithFormat:@"bytes=%zd-", self.currentSize] forHTTPHeaderField:@"Range"];

    // 4.设置请求体信息,字符串--->NSData
    request.HTTPBody = [@"username=gzp&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];

    // 5.发送异步请求
    /*
      第一个参数:请求对象
      第二个参数:队列 决定代码块completionHandler的调用线程
      第三个参数:completionHandler 当请求完成(成功|失败)的时候回调
        response:响应头
        data:响应体
        connectionError:错误信息
    */
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

        // 6.解析数据,NSData --->NSString  但是只有这个响应结束之后才能拿到这个数据
        NSLog(@"带参post返回数据=%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        }];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值