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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM