程序员

iOS 网络访问 - NSURLSession

2016-04-05  本文已影响263人  苏xiao孬

NSURLSession 概述

NSURLSession 的 Task

NSURLSessionDataTask

GET 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php?username=username&password=pwd"];
    // data 或者 request 都是可以的
    NSURLSessionDataTask *taskGET = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil && data.length > 0) {
            NSLog(@"data -- %@", data);
        } else {
            NSLog(@"error -- %@", error);
            NSLog(@"response -- %@", response);
        }
    }];
    [taskGET resume];

POST 请求

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/login.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSData *requestBody = [@"username=username&password=pwd" dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = requestBody;
    NSURLSessionDataTask *taskPOST = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil && data.length > 0) {
            NSLog(@"data -- %@", data);
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"result -- %@", result);
        } else {
            NSLog(@"error -- %@", error);
            NSLog(@"response -- %@", response);
        }
    }];
    [taskPOST resume];
NSURLSessionUploadTask

POST 请求

#define kBoundary @"suxiaonao"
- (void)testSessionUploadTask {
    // create URL
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/post/upload.php"];
    // create POST request
    // 上传一般不会用到 GET 请求
    // 首先,字面理解 POST 就更合适一些
    // 其次,GET 请求会把请求体拼接在 URL 后面,虽然 HTTP 没有限制 URL 的长度,但是,服务器和浏览器会有限制
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // request method
    request.HTTPMethod = @"POST";
    // request head setValue: forHTTPHeaderField:
    // 这儿需要设置一下 HTTPHeaderField,感觉是和 kBoundary 有关,因为后面拼接请求体的时候也是需要用到 kBoundary 的,如果我们在这儿给某个 HTTPHeaderField 赋值了,就会替换掉默认值,并且需要注意大小写敏感
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kBoundary] forHTTPHeaderField:@"Content-Type"];
    // request body
    // connection 是把上传数据放在请求体里面,session 会把上传数据放在 uploadTaskWithRequest: 这个方法的第二个参数里面
    // session send upload
    // dataWithFieldName: 就是在做请求体拼接
    NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:[self dataWithFieldName:@"userfile" fileName:@"cba.txt" fileContent:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"abc.txt" ofType:nil] encoding:NSUTF8StringEncoding error:NULL]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil && data.length > 0) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            NSLog(@"result -- %@", result);
        } else {
            NSLog(@"error -- %@", error);
        }
    }];
    
    [uploadTask resume];
}

dataWithFieldName: fileName: fileContent: 方法实现

//-----------------------------1499715155697045246716155137
//Content-Disposition: form-data; name="userfile"; filename="abc.txt"
//Content-Type: text/plain
//
//Hello!!
//-----------------------------1499715155697045246716155137--
- (NSData *)dataWithFieldName:(NSString *)fieldName fileName:(NSString *)fileName fileContent:(NSString *)fileContent {
    NSMutableString *stringM = [NSMutableString string];
    [stringM appendFormat:@"--%@\r\n", kBoundary];
    [stringM appendFormat:@"Content-Disposition: form-data; name=%@; filename=%@\r\n", fieldName, fileName];
    // Content-Type 有很多,如果不确定,写 application/octet-strea 就好
//    [stringM appendString:@"Content-Type: text/plain\r\n\r\n"];
//    [stringM appendString:@"Content-Type: image/png\r\n\r\n"];
    [stringM appendString:@"Content-Type: application/octet-strea\r\n\r\n"];
    [stringM appendFormat:@"%@\r\n", fileContent];
    [stringM appendFormat:@"--%@--\r\n\r\n", kBoundary];
    NSData *data = [stringM.copy dataUsingEncoding:NSUTF8StringEncoding];
    
    return data;
}
NSURLSessionDownloadTask
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/files.zip"];
    // 这儿用的是 defaultSessionConfiguration
    NSURLSession *downloadSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    NSURLSessionDownloadTask *downloadTask = [downloadSession downloadTaskWithURL:url];
    [downloadTask resume];
    // 然后根据需要实现代理方法就好
NSURLSession 和 NSURLConnection 下载比较
上一篇下一篇

猜你喜欢

热点阅读