【iOS开发-网络】使用NSURLSessionDataTask发送get和post请求

NSURLSessionDataTask是iOS7以后才会有的,是苹果为取代NSURLConnection所出

get请求

//得到session对象
NSURLSession *session = [NSURLSession sharedSession];

 NSURL *url = [NSURL URLWithString:@"http://localhost:8080/TFServer/video"];

//创建一个任务
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
       NSLog(@"----%d", data.length);
}];

//开始任务
 [task resume];

post请求

//创建session对象
NSURLSession *session = [NSURLSession sharedSession];

NSURL *url = [NSURL URLWithString:@"http://localhost:8080/TFServer/login"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//设置request  
request.HTTPMethod = @"post";
request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];

//创建任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"------%d", data.length);
    }];

//开始任务    
[task resume];

你可能感兴趣的:(iOS开发)