iOSNSInputStream流上传

来源:互联网 发布:网络安全教育简报 编辑:程序博客网 时间:2024/06/10 23:35

用NSInputStream上传文件

在有些时候我们需要用流的凡是stream和后台传输数据,这个时候就需要用到流上传:

//对于request来说一般我们都不需要传输的数据设置在body中,stream也是一样设置body中,但是他是设置在对应的streamBody中.//平时我们使用的request一般都是NSURLRequest类型的,但是上传stream的时候需要使用到NSMutableRequest中    NSString *fullUrl = [NSString stringWithFormat:@"%@%@?_ct=app",baseUrl ,urlPath];    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:fullUrl]];    request.HTTPMethod = @"POST";    request.HTTPBodyStream = inputSteam;    //需要在head中设置流使用的Content-Type    [request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];    //进行网络的上传(AFN不太支持同步的上传,所以下边这个是用NSURLConnection实现的同步方法)    NSError *error = nil;    NSURLResponse *reponse = [[NSURLResponse alloc] init];   NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&reponse error:&error];    if (data.length>0 && !error) {        //请求成功    } else if (error){      //请求失败    }
原创粉丝点击