首页 > 代码库 > NSURLSession的用法

NSURLSession的用法

 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

  

    //[self getTest];

    [self postTest];

}

 

-(void) getTest{

    NSURLSession *session = [NSURLSession sharedSession];

    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"];

    

    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"%d",data.length);

        

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

        NSLog(@"%@",dict);

    }];

    [task resume];

}

-(void) postTest{

    NSURLSession *session = [NSURLSession sharedSession];

    //url = http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON

    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];

    

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    

    request.HTTPMethod=@"POST";

    request.HTTPBody = [@"username=123&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];

 

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

        NSLog(@"___%@",dict);

    }];

    [task resume];

 

 

}

NSURLSession的用法