• NSURLSession发送POST请求


    #import "ViewController.h"
    
    @interface ViewController ()<NSURLSessionDataDelegate>
    
    @property (nonatomic, strong) NSMutableData   *totalData;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        
        self.totalData = [[NSMutableData alloc]init];
    }
    
    -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
    {
    //    [self sendPost];
        [self sendPostWithDelegate];
        
    }
    
    -(void)sendPost
    {
        //直接发送POST请求
        NSURL *url = [NSURL URLWithString:@"http://www.yahoo.com"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        
        NSString *username = @"zhaosi";
        NSString *password = @"lsp188";
        NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@",username,password];
        request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error == nil) {
                
                NSString *resultStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"-------%lu",resultStr.length);
            }
            else
            {
                NSLog(@"%@",error.description);
            }
        }];
        //必须启动任务,否则不会走block中的回调
        [dataTask resume];
    }
    
    -(void)sendPostWithDelegate
    {//通过代理完成请求
        NSURL *url = [NSURL URLWithString:@"http://www.yahoo.com"];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        
        NSString *username = @"zhaosi";
        NSString *password = @"lsp188";
        NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@",username,password];
        request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
        
        //自定义会话对象设置代理,
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];//设置代理方法在哪个线程执行
        
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
        [dataTask resume];
    }
    
    
    #pragma mark NSURLConnectionDataDelegate
    - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
    {//接收到服务器响应后,调用的方法
        NSLog(@"didReceiveResponse");
        //需要通过调用completionHandler告诉系统应该如何处理服务器返回的数据
        completionHandler(NSURLSessionResponseAllow);//NSURLSessionResponseAllow表示接收返回的数据
    }
    
    -(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
    {//接收到服务器响应数据的时候会调用,该方法可能调用多次
        
        [self.totalData appendData:data];
        NSLog(@"%lu---",self.totalData.length);
    }
    
    -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
    {//请求完成 或者失败的时候调用
        NSLog(@"didCompleteWithError");
        //在这里 解析数据
        NSLog(@"%@",[[NSString alloc]initWithData:self.totalData encoding:NSUTF8StringEncoding]);
    }
    
    @end
  • 相关阅读:
    CSS3 3D的总结(初学者易懂)
    BAT面试算法精品课直通BAT面试算法精品课购买优惠码-牛客网
    深度学习UFLDL老教程笔记1 稀疏自编码器Ⅱ
    深度学习UFLDL老教程笔记1 稀疏自编码器Ⅰ
    算法分析之函数渐近分析
    调用WebServices报错,请求“System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”类型的权限已失败。
    很久之前写的 ,突然想放上去
    ASP.NET Core – Web API 冷知识
    ASP.NET Core C# 反射 & 表达式树 (第三篇)
    ASP.NET Core C# 反射 & 表达式树 (第二篇)
  • 原文地址:https://www.cnblogs.com/dashengios/p/10558921.html
Copyright © 2020-2023  润新知