//
// ASIFormDataRequest.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 07/11/2008.
// Copyright 2008-2009 All-Seeing Interactive. All rights reserved.
// #import "ASIFormDataRequest.h" // Private stuff
@interface ASIFormDataRequest ()
- (void)buildMultipartFormDataPostBody;
- (void)buildURLEncodedPostBody;
- (void)appendPostString:(NSString *)string; @property (retain) NSMutableArray *postData;
@property (retain) NSMutableArray *fileData; #if DEBUG_FORM_DATA_REQUEST
- (void)addToDebugBody:(NSString *)string;
@property (retain, nonatomic) NSString *debugBodyString;
#endif @end @implementation ASIFormDataRequest #pragma mark utilities
- (NSString*)encodeURL:(NSString *)string
{
NSString *newString = [NSMakeCollectable(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding]))) autorelease];
if (newString) {
return newString;
}
return @"";
} #pragma mark init / dealloc + (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
} - (id)initWithURL:(NSURL *)newURL
{
self = [super initWithURL:newURL];
[self setPostFormat:ASIURLEncodedPostFormat];
[self setStringEncoding:NSUTF8StringEncoding];
[self setRequestMethod:@"POST"];
return self;
} - (void)dealloc
{
#if DEBUG_FORM_DATA_REQUEST
[debugBodyString release];
#endif [postData release];
[fileData release];
[super dealloc];
} #pragma mark setup request - (void)addPostValue:(id <NSObject>)value forKey:(NSString *)key
{
if (!key) {
return;
}
if (![self postData]) {
[self setPostData:[NSMutableArray array]];
}
NSMutableDictionary *keyValuePair = [NSMutableDictionary dictionaryWithCapacity:];
[keyValuePair setValue:key forKey:@"key"];
[keyValuePair setValue:[value description] forKey:@"value"];
[[self postData] addObject:keyValuePair];
} - (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key
{
// Remove any existing value
NSUInteger i;
for (i=; i<[[self postData] count]; i++) {
NSDictionary *val = [[self postData] objectAtIndex:i];
if ([[val objectForKey:@"key"] isEqualToString:key]) {
[[self postData] removeObjectAtIndex:i];
i--;
}
}
[self addPostValue:value forKey:key];
} - (void)addFile:(NSString *)filePath forKey:(NSString *)key
{
[self addFile:filePath withFileName:nil andContentType:nil forKey:key];
} - (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
BOOL isDirectory = NO;
BOOL fileExists = [[[[NSFileManager alloc] init] autorelease] fileExistsAtPath:filePath isDirectory:&isDirectory];
if (!fileExists || isDirectory) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"No file exists at %@",filePath],NSLocalizedDescriptionKey,nil]]];
} // If the caller didn't specify a custom file name, we'll use the file name of the file we were passed
if (!fileName) {
fileName = [filePath lastPathComponent];
} // If we were given the path to a file, and the user didn't specify a mime type, we can detect it from the file extension
if (!contentType) {
contentType = [ASIHTTPRequest mimeTypeForFileAtPath:filePath];
}
[self addData:filePath withFileName:fileName andContentType:contentType forKey:key];
} - (void)setFile:(NSString *)filePath forKey:(NSString *)key
{
[self setFile:filePath withFileName:nil andContentType:nil forKey:key];
} - (void)setFile:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
// Remove any existing value
NSUInteger i;
for (i=; i<[[self fileData] count]; i++) {
NSDictionary *val = [[self fileData] objectAtIndex:i];
if ([[val objectForKey:@"key"] isEqualToString:key]) {
[[self fileData] removeObjectAtIndex:i];
i--;
}
}
[self addFile:data withFileName:fileName andContentType:contentType forKey:key];
} - (void)addData:(NSData *)data forKey:(NSString *)key
{
[self addData:data withFileName:@"file" andContentType:nil forKey:key];
} - (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
if (![self fileData]) {
[self setFileData:[NSMutableArray array]];
}
if (!contentType) {
contentType = @"application/octet-stream";
} NSMutableDictionary *fileInfo = [NSMutableDictionary dictionaryWithCapacity:];
[fileInfo setValue:key forKey:@"key"];
[fileInfo setValue:fileName forKey:@"fileName"];
[fileInfo setValue:contentType forKey:@"contentType"];
[fileInfo setValue:data forKey:@"data"]; [[self fileData] addObject:fileInfo];
} - (void)setData:(NSData *)data forKey:(NSString *)key
{
[self setData:data withFileName:@"file" andContentType:nil forKey:key];
} - (void)setData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
// Remove any existing value
NSUInteger i;
for (i=; i<[[self fileData] count]; i++) {
NSDictionary *val = [[self fileData] objectAtIndex:i];
if ([[val objectForKey:@"key"] isEqualToString:key]) {
[[self fileData] removeObjectAtIndex:i];
i--;
}
}
[self addData:data withFileName:fileName andContentType:contentType forKey:key];
} - (void)buildPostBody
{
if ([self haveBuiltPostBody]) {
return;
} #if DEBUG_FORM_DATA_REQUEST
[self setDebugBodyString:@""];
#endif if (![self postData] && ![self fileData]) {
[super buildPostBody];
return;
}
if ([[self fileData] count] > ) {
[self setShouldStreamPostDataFromDisk:YES];
} if ([self postFormat] == ASIURLEncodedPostFormat) {
[self buildURLEncodedPostBody];
} else {
[self buildMultipartFormDataPostBody];
} [super buildPostBody]; #if DEBUG_FORM_DATA_REQUEST
ASI_DEBUG_LOG(@"%@",[self debugBodyString]);
[self setDebugBodyString:nil];
#endif
} - (void)buildMultipartFormDataPostBody
{
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"\r\n==== Building a multipart/form-data body ====\r\n"];
#endif NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding([self stringEncoding])); // We don't bother to check if post data contains the boundary, since it's pretty unlikely that it does.
CFUUIDRef uuid = CFUUIDCreate(nil);
NSString *uuidString = [(NSString*)CFUUIDCreateString(nil, uuid) autorelease];
CFRelease(uuid);
NSString *stringBoundary = [NSString stringWithFormat:@"0xKhTmLbOuNdArY-%@",uuidString]; [self addRequestHeader:@"Content-Type" value:[NSString stringWithFormat:@"multipart/form-data; charset=%@; boundary=%@", charset, stringBoundary]]; [self appendPostString:[NSString stringWithFormat:@"--%@\r\n",stringBoundary]]; // Adds post data
NSString *endItemBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary];
NSUInteger i=;
for (NSDictionary *val in [self postData]) {
[self appendPostString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",[val objectForKey:@"key"]]];
[self appendPostString:[val objectForKey:@"value"]];
i++;
if (i != [[self postData] count] || [[self fileData] count] > ) { //Only add the boundary if this is not the last item in the post body
[self appendPostString:endItemBoundary];
}
} // Adds files to upload
i=;
for (NSDictionary *val in [self fileData]) { [self appendPostString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", [val objectForKey:@"key"], [val objectForKey:@"fileName"]]];
[self appendPostString:[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [val objectForKey:@"contentType"]]]; id data = [val objectForKey:@"data"];
if ([data isKindOfClass:[NSString class]]) {
[self appendPostDataFromFile:data];
} else {
[self appendPostData:data];
}
i++;
// Only add the boundary if this is not the last item in the post body
if (i != [[self fileData] count]) {
[self appendPostString:endItemBoundary];
}
} [self appendPostString:[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary]]; #if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"==== End of multipart/form-data body ====\r\n"];
#endif
} - (void)buildURLEncodedPostBody
{ // We can't post binary data using application/x-www-form-urlencoded
if ([[self fileData] count] > ) {
[self setPostFormat:ASIMultipartFormDataPostFormat];
[self buildMultipartFormDataPostBody];
return;
} #if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"\r\n==== Building an application/x-www-form-urlencoded body ====\r\n"];
#endif NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding([self stringEncoding])); [self addRequestHeader:@"Content-Type" value:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@",charset]]; NSUInteger i=;
NSUInteger count = [[self postData] count]-;
for (NSDictionary *val in [self postData]) {
NSString *data = [NSString stringWithFormat:@"%@=%@%@", [self encodeURL:[val objectForKey:@"key"]], [self encodeURL:[val objectForKey:@"value"]],(i<count ? @"&" : @"")];
[self appendPostString:data];
i++;
}
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"\r\n==== End of application/x-www-form-urlencoded body ====\r\n"];
#endif
} - (void)appendPostString:(NSString *)string
{
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:string];
#endif
[super appendPostData:[string dataUsingEncoding:[self stringEncoding]]];
} #if DEBUG_FORM_DATA_REQUEST
- (void)appendPostData:(NSData *)data
{
[self addToDebugBody:[NSString stringWithFormat:@"[%lu bytes of data]",(unsigned long)[data length]]];
[super appendPostData:data];
} - (void)appendPostDataFromFile:(NSString *)file
{
NSError *err = nil;
unsigned long long fileSize = [[[[[[NSFileManager alloc] init] autorelease] attributesOfItemAtPath:file error:&err] objectForKey:NSFileSize] unsignedLongLongValue];
if (err) {
[self addToDebugBody:[NSString stringWithFormat:@"[Error: Failed to obtain the size of the file at '%@']",file]];
} else {
[self addToDebugBody:[NSString stringWithFormat:@"[%llu bytes of data from file '%@']",fileSize,file]];
} [super appendPostDataFromFile:file];
} - (void)addToDebugBody:(NSString *)string
{
if (string) {
[self setDebugBodyString:[[self debugBodyString] stringByAppendingString:string]];
}
}
#endif #pragma mark NSCopying - (id)copyWithZone:(NSZone *)zone
{
ASIFormDataRequest *newRequest = [super copyWithZone:zone];
[newRequest setPostData:[[[self postData] mutableCopyWithZone:zone] autorelease]];
[newRequest setFileData:[[[self fileData] mutableCopyWithZone:zone] autorelease]];
[newRequest setPostFormat:[self postFormat]];
[newRequest setStringEncoding:[self stringEncoding]];
[newRequest setRequestMethod:[self requestMethod]];
return newRequest;
} @synthesize postData;
@synthesize fileData;
@synthesize postFormat;
@synthesize stringEncoding;
#if DEBUG_FORM_DATA_REQUEST
@synthesize debugBodyString;
#endif
@end

断点续传队列和本地持久化(iOS源码)的更多相关文章

  1. 消息队列的一些场景及源码分析,RocketMQ使用相关问题及性能优化

    前文目录链接参考: 消息队列的一些场景及源码分析,RocketMQ使用相关问题及性能优化 https://www.cnblogs.com/yizhiamumu/p/16694126.html 消息队列 ...

  2. ios源码-ios游戏源码-ios源码下载

    游戏源码   一款休闲类的音乐小游戏源码 该源码实现了一款休闲类的音乐小游戏源码,该游戏的源码很简单,而且游戏的玩法也很容易学会,只要我们点击视图中的grid,就可以 人气:2943运行环境:/Xco ...

  3. EarthWarrior3D游戏ios源码

    这是一款不错的ios源码源码,EarthWarrior3D游戏源码, 并且游戏源代码支持多平台. 适用于cocos v2.1.0.0版本 源码下载:http://code.662p.com/view/ ...

  4. 非常不错的点餐系统应用ios源码完整版

    该源码是一款非常不错的点餐系统应用,应用源码齐全,运行起来非常不错,基本实现了点餐的一些常用的功能,而且界面设计地也很不错,是一个不错的ios应用学习的例子,喜欢的朋友可以下载学习看看,更多ios源码 ...

  5. android NDK开发在本地C/C++源码中设置断点单步调试具体教程

    近期在学android NDK开发,折腾了一天,最终可以成功在ADT中设置断点单步调试本地C/C++源码了.网上关于这方面的资料太少了,并且大都不全,并且调试过程中会出现各种各样的问题,真是非常磨人. ...

  6. 《你是我的小羊驼》游戏ios源码

    <ignore_js_op> <ignore_js_op> <ignore_js_op> <ignore_js_op>源码下载:http://code. ...

  7. iOS源码博文集锦1

    iOS精选源码 iOS一种弹出视图效果带动画 导航栏显示渐变色,类似qq一样 一分钟找到重力方向 简单高度自定义的日历.可根据项目的需求灵活修改布局 类似于UITableView且极简的图片浏览器 小 ...

  8. 基于ffmpeg 直播推流和播放rtmp (IOS源码)

    ios直播推流每秒能达到30帧,比安卓要强,视频采用软编码的话手机会发烫,得采用码编码,播放视频采用opengl渲染. ffmpeg初始化代码如下: int init_Code(int width, ...

  9. 一个3D ar打飞机的游戏iOS源码

    这是国内目前第一款集合了AR实景,3D游戏和人脸识别的射击游戏,通过旋转和改变手机的角度与位置,所有的射击操作都靠手势来完成,目前所有的源码全部都在这里.appStore地址:https://itun ...

随机推荐

  1. elk系列2之multiline模块的使用【转】

    preface 上回说道了elk的安装以及kibana的简单搜索语法,还有logstash的input,output的语法,但是我们在使用中发现了一个问题,我们知道,elk是每一行为一个事件,像Jav ...

  2. 分布式队列Celery入门

    Celery 是一个简单.灵活且可靠的,处理大量消息的分布式系统,并且提供维护这样一个系统的必需工具.它是一个专注于实时处理的任务队列,同时也支持任务调度.Celery 是语言无关的,虽然它是用 Py ...

  3. Machine Learning系列--深入理解拉格朗日乘子法(Lagrange Multiplier) 和KKT条件

    在求取有约束条件的优化问题时,拉格朗日乘子法(Lagrange Multiplier) 和KKT条件是非常重要的两个求取方法,对于等式约束的优化问题,可以应用拉格朗日乘子法去求取最优值:如果含有不等式 ...

  4. jQuery对的表单数据序列化和校验

    jQuery对的表单数据序列化和校验 表单序列化 如果想让表单通过ajax异步提交,那么首先我们要通过js获取到每个表单中输入的值,如果表单项比较多的话,是一件很麻烦,很痛苦的事情,那么我们可以通过j ...

  5. java中常见异常汇总(根据自己遇到的异常不定时更新)

    1.java.lang.ArrayIndexOutOfBoundsException:N(数组索引越界异常.如果访问数组元素时指定的索引值小于0,或者大于等于数组的长度,编译程序不会出现任何错误,但运 ...

  6. 网页查看源码中&lt;div&gt的含义

    代码如下: /** HTML转义 **/ String s = HtmlUtils.htmlEscape("<div>hello world</div><p&g ...

  7. 使用Jackson来实现Java对象与JSON的相互转换的教程

    一.入门Jackson中有个ObjectMapper类很是实用,用于Java对象与JSON的互换.1.JAVA对象转JSON[JSON序列化] 1 2 3 4 5 6 7 8 9 10 11 12 1 ...

  8. (My)SQL

    1.SQL语句分类 DDL(Data Definition Languages)语句:用来创建 删除 修改数据库.表.列.索引等数据库对象.常用的语句关键字主要包括create.drop.alter等 ...

  9. 20165301 预备作业二:学习基础和C语言基础调查

    <做中学>读后感及C语言学习调查 读<做中学>有感 娄老师在文章中多次提到「做中学(Learning By Doing)」的概念,并通过娄老师自己的减肥经历.五笔练习经历.乒乓 ...

  10. python基础(5)---整型、字符串、列表、元组、字典内置方法和文件操作介绍

    对于python而言,一切事物都是对象,对象是基于类创建的,对象继承了类的属性,方法等特性 1.int 首先,我们来查看下int包含了哪些函数 # python3.x dir(int) # ['__a ...