博客> iOS之数据的上传
iOS之数据的上传
2019-12-10 11:35 评论:0 阅读:1225 syfuxi
ios NSURLSession 数据的上传

数据的上传:

这里以在新浪微博上发送一条微博为例, 通过NSURLSession类的方法来完成 主要用到下面两种方法:

// fileURL: 上传的文件路径
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler

// fromData:上传文件的data路径
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest
*)request
fromData:(NSData *)bodyData
completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler

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

HTTP请求头 .... multipart/form-data; charset=utf-8;boundary=AaB03x .... HTTP请求体 --AaB03x Content-Disposition: form-data; name="key1" value1 --AaB03x Content-disposition: form-data; name="key2" value2 --AaB03x

图片数据 ----AaB03x--

想要向新浪微博发送消息,前提是你要拿到他的接口的钥匙。 access_token:(使用的权限) 相当于进入各个接口的钥匙,只有拿到这个钥匙,才可以拥有使用接口的权限

举例1: 向新浪微博发送一天简单消息,思路是讲我们需要发送的内容放进请求体中,然后发送出去就行。具体必须要求哟啊有的参数可以参见新浪微博开放平台API文档。

// 1 url
NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/2/statuses/update.json"];

//2 request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//请求方式
request.HTTPMethod = @"POST";

//请求体

NSString *status = @"hello";
NSString *params = [NSString stringWithFormat:@"access_token=%@&status=%@",Access_Token,status];

NSData *bodyData = [params dataUsingEncoding:NSUTF8StringEncoding];

//将数据放进请求体中
request.HTTPBody = bodyData;

//3 session
NSURLSession *session = [NSURLSession sharedSession];

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

    NSLog(@"response = %@",response);

}];
//5 resume
[task resume];

举例2: 向新浪微博发送一条带图片的微博 依然是5步

1.上传到哪里

 NSURL *url = [NSURL URLWithString:@"https://upload.api.weibo.com/2/statuses/upload.json"];

2.创建一个请求,配置好相关属性

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];

//    [request setHTTPBody:bodydata];

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.执行任务

[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;

}
收藏
0
sina weixin mail 回到顶部