zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    OpenLayers 添加OpenStreetMap(OSM)瓦片层示例
    [转]Net Framework引路蜂地图开发示例
    SVG关注复杂图形的网页绘制技术
    解决Easyui1.3.3 IE8兼容性问题
    Ajax学习教程在线阅读
    判断访问站点的浏览器类型
    修改TOMCAT服务器图标为应用LOGO
    ArcGIS学习推荐基础教程摘录
    Jquery html页面处理基础
    android AppWidget的使用以及利用TimerTask实现widget的定时更新
  • 原文地址:https://www.cnblogs.com/dashengios/p/10558921.html
Copyright © 2011-2022 走看看