使用CFNetwork实现的http库,能同时在iphone和macos下使用:http://allseeing-i.com/ASIHTTPRequest/

他提供以下功能:

  • 向服务器发送或者从服务器获取数据的接口
  • 下载数据,可以保存到内存里,或者保存的磁盘的文件里。
  • 以POST的方式提交本地文件,和HTML文件输入机制兼容。
  • 以流的方式把磁盘里的文件发送的服务器
  • 断点续传
  • 方便的访问request 和 response HTTP headers
  • 进度代理,利用NSProgressIndicators and UIProgressViews显示上传和下载的进度
  • 自动管理上传和下载的进度。
  • 支持Cookie
  • Requests可在后台运行

  • response data 和 request bodies支持GZIP

  • ASIWebPageRequest-下载整个网页。

  • 支持Amazon S3
  • 支持Rackspace Cloud Files
  • 支持客户端证书
  • 支持长连接
  • 支持同步和异步请求
  • 可以通过代理获取request状态的变化。

1、使用方法

1.1同步请求:

  1. - (IBAction)grabURL:(id)sender
  2. {
  3. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
  4. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  5. [request startSynchronous];
  6. NSError *error = [request error];
  7. if (!error) {
  8. NSString *response = [request responseString];
  9. }
  10. }

a, 用requestWithURL快捷方法获取ASIHTTPRequest的一个实例
b, startSynchronous 方法启动同步访问,
c, 由于是同步请求,没有基于事件的回调方法,所以从request的error属性获取错误信息。
d, responseString,为请求的返回NSString信息。

1.2异步请求:

  1. - (IBAction)grabURLInBackground:(id)sender
  2. {
  3. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
  4. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  5. [request setDelegate:self];
  6. [request startAsynchronous];
  7. }
  8.  
  9. - (void)requestFinished:(ASIHTTPRequest *)request
  10. {
  11. // Use when fetching text data
  12. NSString *responseString = [request responseString];
  13.  
  14. // Use when fetching binary data
  15. NSData *responseData = [request responseData];
  16. }
  17.  
  18. - (void)requestFailed:(ASIHTTPRequest *)request
  19. {
  20. NSError *error = [request error];
  21. }

a,与上面不同的地方是指定了一个 “delegate”,并用startAsynchronous来启动网络请求。
b,在这里实现了两个delegate的方法,当数据请求成功时会调用requestFinished,请求失败时(如网络问题或服务器内部错误)会调用requestFailed。

1.3队列请求:

提供了一个对异步请求更加精准丰富的控制。适用于多个请求按顺序执行。

  1. if (!networkQueue) {
  2. networkQueue = [[ASINetworkQueue alloc] init];
  3. }
  4. failed = NO;
  5. [networkQueue reset];
  6. [networkQueue setDownloadProgressDelegate:progressIndicator];
  7. [networkQueue setRequestDidFinishSelector:@selector(imageFetchComplete:)];
  8. [networkQueue setRequestDidFailSelector:@selector(imageFetchFailed:)];
  9. [networkQueue setShowAccurateProgress:[accurateProgress isOn]];
  10. [networkQueue setDelegate:self];
  11.  
  12. ASIHTTPRequest *request;
  13. request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/images/small-image.jpg"]];
  14. [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"1.png"]];
  15. [request setDownloadProgressDelegate:imageProgressIndicator1];
  16. [request setUserInfo:[NSDictionary dictionaryWithObject:@"request1" forKey:@"name"]];
  17. [networkQueue addOperation:request];
  18.  
  19. request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/images/medium-image.jpg"]] autorelease];
  20. [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"2.png"]];
  21. [request setDownloadProgressDelegate:imageProgressIndicator2];
  22. [request setUserInfo:[NSDictionary dictionaryWithObject:@"request2" forKey:@"name"]];
  23. [networkQueue addOperation:request];
  24.  
  25. request = [[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/images/large-image.jpg"]] autorelease];
  26. [request setDownloadDestinationPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"3.png"]];
  27. [request setDownloadProgressDelegate:imageProgressIndicator3];
  28. [request setUserInfo:[NSDictionary dictionaryWithObject:@"request3" forKey:@"name"]];
  29. [networkQueue addOperation:request];
  30.  
  31. [networkQueue go];

1.4使用block:

  1. - (IBAction)grabURLInBackground:(id)sender
  2. {
  3. NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
  4. __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  5. [request setCompletionBlock:^{
  6. // Use when fetching text data
  7. NSString *responseString = [request responseString];
  8.  
  9. // Use when fetching binary data
  10. NSData *responseData = [request responseData];
  11. }];
  12. [request setFailedBlock:^{
  13. NSError *error = [request error];
  14. }];
  15. [request startAsynchronous];
  16. }

1.4取消异步请求:
首先,同步请求是不能取消的。
其次,不管是队列请求,还是简单的异步请求,全部调用[ request cancel ]来取消请求。

1.5向服务器上传数据:

  1. ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  2. [request setPostValue:@"Ben" forKey:@"first_name"];
  3. [request setPostValue:@"Copsey" forKey:@"last_name"];
  4. [request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];
  5. [request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];
  6. //如果要发送自定义数据:
  7. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  8. [request appendPostData:[@"This is my data" dataUsingEncoding:NSUTF8StringEncoding]];
  9. // Default becomes POST when you use appendPostData: / appendPostDataFromFile: / setPostBody:
  10. [request setRequestMethod:@"PUT"];

1.6下载文件:

通过设置request的setDownloadDestinationPath,可以设置下载文件用的下载目标目录。
首先,下载过程文件会保存在temporaryFileDownloadPath目录下。如果下载完成会做以下事情:
1,如果数据是压缩的,进行解压,并把文件放在downloadDestinationPath目录中,临时文件被删除
2,如果下载失败,临时文件被直接移到downloadDestinationPath目录,并替换同名文件。

如果你想获取下载中的所有数据,可以实现delegate中的request:didReceiveData:方法。但如果你实现了这个方法,request在下载完后,request并不把文件放在downloadDestinationPath中,需要手工处理。

1.7获取请求进度:

有两个回调方法可以获取请求进度,
1,downloadProgressDelegate,可以获取下载进度
2,uploadProgressDelegate,可以获取上传进度

1.8cookie:

如果Cookie存在的话,会把这些信息放在NSHTTPCookieStorage容器中共享,并供下次使用。
你可以用[ ASIHTTPRequest setSessionCookies:nil ] ; 清空所有Cookies。
当然,你也可以取消默认的Cookie策略,而使自定义的Cookie:

  1. NSDictionary *properties = [[[NSMutableDictionary alloc] init] autorelease];
  2. [properties setValue:[@"Test Value" encodedCookieValue] forKey:NSHTTPCookieValue];
  3. [properties setValue:@"ASIHTTPRequestTestCookie" forKey:NSHTTPCookieName];
  4. [properties setValue:@".allseeing-i.com" forKey:NSHTTPCookieDomain];
  5. [properties setValue:[NSDate dateWithTimeIntervalSinceNow:*] forKey:NSHTTPCookieExpires];
  6. [properties setValue:@"/asi-http-request/tests" forKey:NSHTTPCookiePath];
  7. NSHTTPCookie *cookie = [[[NSHTTPCookie alloc] initWithProperties:properties] autorelease];
  8.  
  9. //This url will return the value of the ’ASIHTTPRequestTestCookie’ cookie
  10. url = [NSURL URLWithString:@"http://allseeing-i.com/ASIHTTPRequest/tests/read_cookie"];
  11. request = [ASIHTTPRequest requestWithURL:url];
  12. [request setUseCookiePersistence:NO];
  13. [request setRequestCookies:[NSMutableArray arrayWithObject:cookie]];
  14. [request startSynchronous];
  15.  
  16. //Should be: I have ’Test Value’ as the value of ’ASIHTTPRequestTestCookie’
  17. NSLog(@“%@”,[request responseString]);

1.9断点续传:

  1. [ request setAllowResumeForFileDownloads:YES ];
  2. [ request setDownloadDestinationPath:downloadPath ];

2.0其他:

是否有网络请求:

  1. [ ASIHTTPRequest isNetworkInUse ]

是否显示网络请求信息在status bar上:

  1. [ ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO ];

设置请求超时时,设置重试的次数:

  1. [ request setNumberOfTimesToRetryOnTimeout: ];

后台执行:

  1. [ request setShouldContinueWhenAppEntersBackground:YES ];

参考:

1、http://wiki.magiche.net/pages/viewpage.action?pageId=2064410

2、http://sev7n.net/index.php/615.html

3、http://allseeing-i.com/ASIHTTPRequest/How-to-use

2、源码解读:

ASIHTTPRequest是NSOperation的子类。

发起同步请求的过程是:

  1. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
  2. [request startSynchronous];
  1. - (void)startSynchronous
  2. {
  3. #if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
  4. NSLog(@"Starting synchronous request %@",self);
  5. #endif
  6. [self setSynchronous:YES];
  7. [self setRunLoopMode:ASIHTTPRequestRunLoopMode];
  8. [self setInProgress:YES];
  9.  
  10. if (![self isCancelled] && ![self complete]) {
  11. [self main];
  12. while (!complete) {
  13. [[NSRunLoop currentRunLoop] runMode:[self runLoopMode] beforeDate:[NSDate distantFuture]];
  14. }
  15. }
  16.  
  17. [self setInProgress:NO];
  18. }

在重载的main方法中,建立了一个HTTP request:

  1. request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (CFStringRef)[self requestMethod], (CFURLRef)[self url], [self useHTTPVersionOne] ? kCFHTTPVersion1_0 : kCFHTTPVersion1_1);

kCFAllocatorDefault指定了将使用默认的系统内存管理器创建消息引用,requestMethod指定了消息请求的执行方式,(CFURLRef)[self url]指定将要请求的远程地址,kCFHTTPVersion1_1指定HTTP请求的版本为1.1。CFHTTPMessageCreateRequest函数的返回值就是消息对象的引用。

然后,在startRequest方法中,通过CFReadStreamOpen发送请求

  1. // Start the HTTP connection
  2. CFStreamClientContext ctxt = {, self, NULL, NULL, NULL};
  3. if (CFReadStreamSetClient((CFReadStreamRef)[self readStream], kNetworkEvents, ReadStreamClientCallBack, &ctxt)) {
  4. if (CFReadStreamOpen((CFReadStreamRef)[self readStream])) {
  5. streamSuccessfullyOpened = YES;
  6. }
  7. }

iOS开源项目:asi-http-request的更多相关文章

  1. 直接拿来用!最火的iOS开源项目

    1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是G ...

  2. (转)直接拿来用!最火的iOS开源项目(一)

    1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是G ...

  3. 【转】GitHub平台最火的iOS开源项目——2013-08-25 17

    http://www.cnblogs.com/lhming/category/391396.html 今天,我们将介绍20个在GitHub上非常受开发者欢迎的iOS开源项目,你准备好了吗? 1. AF ...

  4. iOS开源项目

    在结束了GitHub平台上“最受欢迎的Android开源项目”系列盘点之后,我们正式迎来了“GitHub上最受欢迎的iOS开源项目”系列盘点.今天,我们将介绍20个在GitHub上非常受开发者欢迎的i ...

  5. GitHub上最火的40个iOS开源项目

    1. AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS. Mac OS X网络通信类库,现在是 ...

  6. 直接拿来用!最火的iOS开源项目(一)

    直接拿来用!最火的iOS开源项目(一) 发表于2013-06-05 10:17| 39373次阅读| 来源CSDN| 100 条评论| 作者唐小引 iOS开源项目GitHub移动开发最受欢迎的开源项目 ...

  7. GitHub上最受欢迎的iOS开源项目TOP20

    AFNetworking 在众多iOS开源项目中,AFNetworking可以称得上是最受开发者欢迎的库项目.AFNetworking是一个轻量级的iOS.Mac OS X网络通信类库,现在是GitH ...

  8. 十款不容错过的Swift iOS开源项目及介绍

    1.十款不容错过的Swift iOS开源项目. http://www.csdn.net/article/2014-10-16/2822083-swift-ios-open-source-project ...

  9. 直接拿来用!最火的iOS开源项目(一~三)

    结束了GitHub平台上“最受欢迎的Android开源项目”系列盘点之后,我们正式迎来了“GitHub上最受欢迎的iOS开源项目”系列盘点.今天,我们将介绍20个在GitHub上非常受开发者欢迎的iO ...

  10. iOS开源项目周报0105

    由OpenDigg 出品的iOS开源项目周报第四期来啦.我们的iOS开源周报集合了OpenDigg一周来新收录的优质的iOS开发方面的开源项目,方便iOS开发人员便捷的找到自己需要的项目工具等. He ...

随机推荐

  1. java 数组操作方法

    数组操作方法: 实现数组拷贝: 语法:System.arraycopy(源数组名称,源数组拷贝开始索引,目标数组名称,目标数组拷贝数组索引,长度) 数组A:1 . 2 . 3 . 4 . 5 . 6  ...

  2. 八步详解Hibernate的搭建及使用

    本文通过了八个步骤以及一些实例添加用户来介绍Hibernate的搭建和使用,真切的介绍了hibernate的基本用法,其中好多优点等待我们自己去发现,比如hibernate中的缓存机制,映射方案. 1 ...

  3. 2017/11/9 Leetcode 日记

    2017/11/9 Leetcode 日记 566. Reshape the Matrix In MATLAB, there is a very useful function called 'res ...

  4. Java文件签名与验证

    数字签名与验证只需要用户输入三个参数: Ø         原文件 Ø         签名信息文件 Ø         用户名 签名过程: 1.         首先从用户名对应的用户注册文件中读取 ...

  5. java 线程 wait join sleep yield notify notifyall synchronized

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 休息方法 : 在指定时间内 让该线程 暂停, 不会释放 锁标志. 等待方法: 让 该 线 ...

  6. Luogu P3962 [TJOI2013]数字根 st

    题面 我先对数字根打了个表,然后得到了一个结论:\(a\)的数字根=\((a-1)mod 9+1\) 我在询问大佬后,大佬给出了一个简单的证明: \(\because 10^n\equiv 1(mod ...

  7. 【洛谷】P1063 能量项链【区间DP】

    P1063 能量项链 题目描述 在Mars星球上,每个Mars人都随身佩带着一串能量项链.在项链上有N颗能量珠.能量珠是一颗有头标记与尾标记的珠子,这些标记对应着某个正整数.并且,对于相邻的两颗珠子, ...

  8. SCOJ 4493: DNA 最长公共子串 后缀自动机

    4493: DNA 题目连接: http://acm.scu.edu.cn/soj/problem.action?id=4493 Description Deoxyribonucleic acid ( ...

  9. Educational Codeforces Round 10 B. z-sort 构造

    B. z-sort 题目连接: http://www.codeforces.com/contest/652/problem/B Description A student of z-school fo ...

  10. Unity创建asset文件的扩展编辑器

    using UnityEngine; using UnityEditor; using System.IO; public class CreateAsset : EditorWindow { pri ...