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_h2 小时前
【iOS】锁的原理
笔记·学习·macos·ios·objective-c·cocoa·xcode
Digitally3 小时前
将 iPhone 联系人转移到 Infinix 的完整指南
ios·cocoa·iphone
imLix18 小时前
RunLoop 实现原理
前端·ios
归辞...1 天前
「iOS」————设计架构
ios·架构
i紸定i1 天前
解决html-to-image在 ios 上dom里面的图片不显示出来
前端·ios·vue·html·html-to-image
YungFan2 天前
iOS26适配指南之UIButton
ios·swift
红橙Darren2 天前
手写操作系统 - 编译链接与运行
android·ios·客户端
鹏多多.2 天前
flutter-使用device_info_plus获取手机设备信息完整指南
android·前端·flutter·ios·数据分析·前端框架
麦兜*3 天前
【swift】SwiftUI动画卡顿全解:GeometryReader滥用检测与Canvas绘制替代方案
服务器·ios·swiftui·android studio·objective-c·ai编程·swift