ios http网络请求

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

objectivec 复制代码
- (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]);
        }];
}
相关推荐
Magnetic_h13 小时前
【iOS】单例模式
笔记·学习·ui·ios·单例模式·objective-c
归辞...15 小时前
「iOS」——单例模式
ios·单例模式·cocoa
yanling202317 小时前
黑神话悟空mac可以玩吗
macos·ios·crossove·crossove24
归辞...19 小时前
「iOS」viewController的生命周期
ios·cocoa·xcode
crasowas1 天前
Flutter问题记录 - 适配Xcode 16和iOS 18
flutter·ios·xcode
2401_852403551 天前
Mac导入iPhone的照片怎么删除?快速方法讲解
macos·ios·iphone
SchneeDuan1 天前
iOS六大设计原则&&设计模式
ios·设计模式·cocoa·设计原则
羊十一2 天前
C++(C++的文件I/O)
开发语言·c++·cocoa
JohnsonXin2 天前
【兼容性记录】video标签在 IOS 和 安卓中的问题
android·前端·css·ios·h5·兼容性
蒙娜丽宁2 天前
Go语言错误处理详解
ios·golang·go·xcode·go1.19