iOS NSURLSession实现网络请求

发送POST请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"post";
    NSString *body = @"username=123&password=123";
    request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"%@",json);
    }] resume];

发送GET请求

 NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];

[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse *

_Nullable response, NSError * _Nullable error) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"%@",json);
    }] resume];

文件下载

NSURL *url = [NSURL URLWithString:@"abc.hm"];
    
    [[[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSThread currentThread]);
        
        NSLog(@"%@",location);

        NSString *doc = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"123.hm"];
        
        //复制到其他位置
        [[NSFileManager defaultManager] copyItemAtPath:location.path toPath:doc error:NULL];
        
    }] resume];

发布了368 篇原创文章 · 获赞 22 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/BianHuanShiZhe/article/details/105012883