NSURLSessionUploadTask(上传任务)

NSURLSessionUploadTask上传的方法

// fileURL:上传文件的路径
 - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest*)requestfromFile:(NSURL *)fileURLcompletionHandler:(void (^)(NSData *data, NSURLResponse *response,NSError *error))completionHandler
// fromDatadata上传文件的data数据
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest*)requestfromData:(NSData *)bodyDatacompletionHandler:(void (^)(NSData *data, NSURLResponse *response,NSError *error))completionHandler

上传文件,请求包中的数据必须符合如下格式

HTTP请求头:(boundary相当于一个字符串标识符,可以赋值任何字符串)

multipart/form-data; charset=utf-8;boundary=AaB03x
HTTP请求体:(key:键  value:值)
--AaB03x
Content-Disposition: form-data; name="key1"

value1
--AaB03x
Content-disposition: form-data; name="key2"

value2
--AaB03x
Content-disposition: form-data; name="key3"; filename="file"Content-Type: application/octet-stream

//这里加图片数据
--AaB03x--

简单使用demo(利用新浪微博接口发条微博)

#import "ViewController.h"
#define boundary @"asdfasdfas"
#define Access_Token @"2.00LvxxAE33dQxBcfde5ce726QdVfB"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //1 url
    NSURL *url = [NSURL URLWithString:@"https://upload.api.weibo.com/2/statuses/upload.json"];
    
    //2 request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //(1)请求方式
    [request setHTTPMethod:@"POST"];
    
    //(2)请求头
    //上传任务,必须要添加的字段
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; charset=utf-8;boundary=%@",boundary];
    
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    //(3)请求体
    NSString *path = [[NSBundle mainBundle]pathForResource:@"2" ofType:@"jpg"];
    
    NSData *bodydata = [self buildBodyDataWithStatus:@"赞" withPicPath:path];
    
    //3 session
    NSURLSession *session = [NSURLSession sharedSession];
    
    //4 task
    /*
     Request:请求对象
     fromData:请求体
     */
    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:bodydata completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
      //打印出响应体,查看是否发送成功
        NSLog(@"response = %@",response);
        
    }];
    
    //5 resume
    [task resume];
    
}
-(NSData*)buildBodyDataWithStatus:(NSString*)text withPicPath:(NSString *)path{

    //创建可变字符串
    NSMutableString *bodyStr = [NSMutableString string];
    
    //1 access_token
    [bodyStr appendFormat:@"--%@\r\n",boundary];//\n:换行 \n:切换到行首
    [bodyStr appendFormat:@"Content-Disposition: form-data; name=\"access_token\""];
    [bodyStr appendFormat:@"\r\n\r\n"];
    [bodyStr appendFormat:@"%@\r\n",Access_Token];
    
    //2 stutas
    [bodyStr appendFormat:@"--%@\r\n",boundary];//\n:换行 \n:切换到行首
    [bodyStr appendFormat:@"Content-Disposition: form-data; name=\"status\""];
    [bodyStr appendFormat:@"\r\n\r\n"];
    [bodyStr appendFormat:@"%@\r\n",text];
    
    //3 pic
    /*
     --AaB03x
     Content-disposition: form-data; name="pic"; filename="file"
     Content-Type: application/octet-stream
     */
    [bodyStr appendFormat:@"--%@\r\n",boundary];
    [bodyStr appendFormat:@"Content-disposition: form-data; name=\"pic\"; filename=\"file\""];
    [bodyStr appendFormat:@"\r\n"];
    [bodyStr appendFormat:@"Content-Type: application/octet-stream"];
    [bodyStr appendFormat:@"\r\n\r\n"];
    
    
    NSMutableData *bodyData = [NSMutableData data];
    
    //(1)startData
    NSData *startData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [bodyData appendData:startData];
    
    //(2)pic
    NSData *picdata  =[NSData dataWithContentsOfFile:path];
    [bodyData appendData:picdata];
    
    //(3)--Str--
    NSString *endStr = [NSString stringWithFormat:@"\r\n--%@--\r\n",boundary];
    NSData *endData = [endStr dataUsingEncoding:NSUTF8StringEncoding];
    [bodyData appendData:endData];
    
    
    return bodyData;
    
    
}

上传成功

NSURLSessionUploadTask(上传任务)_第1张图片
weibo.png

你可能感兴趣的:(NSURLSessionUploadTask(上传任务))