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]);
        }];
}
相关推荐
2501_915921434 小时前
iOS 虚拟位置设置实战,多工具协同打造精准调试与场景模拟环境
android·ios·小程序·https·uni-app·iphone·webview
QuantumLeap丶5 小时前
《Flutter全栈开发实战指南:从零到高级》- 11 -状态管理Provider
android·flutter·ios
2501_916008895 小时前
App 上架需要什么?从开发者账号到开心上架(Appuploader)免 Mac 上传的完整流程指南
macos·ios·小程序·uni-app·objective-c·cocoa·iphone
QuantumLeap丶1 天前
《Flutter全栈开发实战指南:从零到高级》- 09 -常用UI组件库实战
flutter·ios·dart
2501_915918411 天前
App 上架苹果商店全流程详解 从开发者账号申请到开心上架(Appuploader)跨平台免 Mac 上传实战指南
macos·ios·小程序·uni-app·objective-c·cocoa·iphone
2501_916007471 天前
从零开始学习iOS App开发:Xcode、Swift和发布到App Store完整教程
android·学习·ios·小程序·uni-app·iphone·xcode
Pluto5381 天前
第一个app产品的迭代
ios·github
2501_915921431 天前
iOS 26 CPU 使用率监控策略 多工具协同构建性能探索体系
android·ios·小程序·https·uni-app·iphone·webview
狂团商城小师妹1 天前
JAVA国际版同城打车源码同城服务线下结账系统源码适配PAD支持Android+IOS+H5
android·java·ios·小程序·交友
游戏开发爱好者81 天前
iOS 应用逆向对抗手段,多工具组合实战(iOS 逆向防护/IPA 混淆/无源码加固/Ipa Guard CLI 实操)
android·ios·小程序·https·uni-app·iphone·webview