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]);
        }];
}
相关推荐
恋猫de小郭13 分钟前
React Native 前瞻式重大更新 Skia & WebGPU & ThreeJS,未来可期
android·javascript·flutter·react native·react.js·ios
美狐美颜sdk5 小时前
什么是直播美颜SDK?跨平台安卓、iOS美颜SDK开发实战详解
ios·音视频·美颜sdk·直播美颜sdk
I烟雨云渊T6 小时前
iOS瀑布流布局的实现(swift)
开发语言·ios·swift
鸿蒙布道师1 天前
鸿蒙NEXT开发动画案例3
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
鸿蒙布道师1 天前
AI原生手机:三大技术阵营的终极对决与未来展望
android·人工智能·ios·华为·智能手机·ai-native·hauwei
Echo-潔1 天前
iOS创建Certificate证书、制作p12证书流程
ios·ios 生成app打包证书
yangpipi-2 天前
10.王道_HTTP
网络协议·http·ios
鸿蒙布道师2 天前
鸿蒙NEXT开发动画案例2
android·ios·华为·harmonyos·鸿蒙系统·arkui·huawei
I烟雨云渊T2 天前
iOS 模块化开发流程
ios
刘小哈哈哈2 天前
Lost connect to debugger on ‘iphone‘
ios·iphone