ASIHttpRequest网络使用框架

/********开源库ASI的使用********/
/*依赖的5个库文件: CFNetwork, SystemConfiguration, MobileCoreServices, 和 libz、libxml2
 *ASIHttpRequest 是一款极其强劲的 HTTP 访问开源项目。让简单的 API 完成复 杂的功能,如:异步请求,队列请求,GZIP 压缩,缓存,断点续传,进度跟踪,上传文 件,HTTP 认证。 在新的版本中,还加入了 Objective-C 闭包 Block 的支持,让我们 的代码加轻简灵活。*/
// ·官方网址: http://allseeing-i.com/ASIHTTPRequest/How-to-use
// ·下载地址: https://github.com/pokeb/asi-http-request


/********发起同步请求********/
- (void)synchronousRequest {
    if ([self.urlField.text length] == 0) {
        return; }
    // 初始化一个url
    NSURL *url = [NSURL URLWithString:self.urlField.text];
    // 创建request对象
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    // 设置请求方式
    [request setRequestMethod:@"POST"];
    // 发送一个同步请求
    [request startSynchronous];
    NSError *error = [request error];
    if (!error) {
        // 获取请求数据
        NSString *response = [request responseString]; self.textField.text = response;
    }
}


/********发起异步请求********/
- (void)aSynchronousRequest {
    if ([self.urlField.text length] == 0) {
        return; }
  NSURL
*url = [NSURL URLWithString:self.urlField.text];
  ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; // 发送异步请求 [request startAsynchronous]; } // 数据加载结束delegate - (void)requestFinished:(ASIHTTPRequest *)request { NSString *responseString = [request responseString]; self.textField.text = responseString; } // 数据加载失败delegate - (void)requestFailed:(ASIHTTPRequest *)request { NSError *error = [request error]; } /********Block回调********/ // 设置开始请求回调 - (void)setStartedBlock:(ASIBasicBlock)aStartedBlock; // 设置请求完成回调 - (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock; // 设置请求失败回调 - (void)setFailedBlock:(ASIBasicBlock)aFailedBlock; // 设置数据接受回调,调用多次,每次返回加载的数据 - (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock; //Block回调示例 // 异步请求 - (void)aSynchronousRequest { // 如果url不存在,不执行 if ([self.urlField.text length] == 0) { return; } NSURL *url = [NSURL URLWithString:self.urlField.text]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; // 设置数据请求完成后回调的block [request setCompletionBlock:^{ NSString *responseText = [request responseString]; NSLog(@"%@",responseText); }]; // 发送异步请求 [request startAsynchronous]; } /********设置缓存策略********/ /* * 缓存策略说明 * ASICacheForSessionDurationCacheStoragePolicy 清除上次会话请求的本地缓存数据 * ASICachePermanentlyCacheStoragePolicy 是持久缓存,程序瑕疵启动,缓存仍人存在 */ // 创建缓存对象 ASIDownloadCache *asiCache = [[ASIDownloadCache alloc] init]; // 设置缓存目录,这里设置沙河目录下得Documents目录作为缓存目录 NSString *document = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; [asiCache setStoragePath:document]; // 设置缓存策略 [asiCache setDefaultCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy]; // 创建数据请求对象 ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL: [NSURL  URLWithString:urlString]]; // 设置缓存策略 request.cacheStoragePolicy = ASICachePermanentlyCacheStoragePolicy; // ????????? [request setDownloadCache:cache]; // 开始异步请求网络 [request startAsynchronous]; // 网络数据加载完毕后调用block [request setCompletionBlock:^{ // 打印返回的数据 NSString *responseString = request.responseString; NSLog(@"%@", responseString); // 判断返回的数据是否来自本地缓存 if (request.didUseCachedResponse) { NSLog(@"使用缓存数据"); } else { NSLog(@"请求网络数据"); } }]; /********文件下载*********/ // 设置本地路径path NSString *urlstring = @”http://free2.macx.cn:81/tools/system/CleanMyMac- v1-10-8.dmg”; NSString *filename = [urlstring lastPathComponent]; NSString *path = [NSHomeDirectory() stringByAppendingPathComponent: [NSString stringWithFormat:@"Documents/%@",filename]]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL: [NSURL URLWithString:urlstring]]; // 设置下载路径 [request setDownloadDestinationPath:path]; // 设置下载进度条视图 // 监听下载进度条需要用到kvo [request setDownloadProgressDelegate:self.myProgress]; // 开始异步下载 [request startAsynchronous]; /********请求队列********/ //·ASIHTTPRequest 类是继承于NSOperation, 所以它本身是可以添加到请求队列 中NSOperationQueue。 //·ASI为我们提供了请求队列对象ASINetworkQueue,它继承于NSOperationQueue // 创建请求队列 ASINetworkQueue *queue = [ASINetworkQueue queue]; // 设置并发数 [queue setMaxConcurrentOperationCount:1]; // 将请求添加到队列中 [queue addOperation:request1]; [queue addOperation:request2]; // 执行队列中的请求 [queue go]; /********取消异步请求********/ // 请求取消后,默认按请求失败处理,调用失败的delegate [request cancel]; // 如果不想调用失败后的delegate,则设置 [request clearDelegatesAndCancel]; // 获取下载请求进度delegate downloadProgressDelegate // 获取上传请求进度delegate uploadProgressDelegate /********其他特性********/ // ios4以上,是否开启后台运行 [request setShouldContinueWhenAppEntersBackground:YES]; // 设置超时自动重试最大次数为2 [request setNumberOfTimesToRetryOnTimeout:2]; // 获取cookies NSMutableArray *cookies = [request requestCookies]; // 清除cookies [ASIHTTPRequest clearSession]; // 设置cookies [ASIHTTPRequest setSessionCookies:cookies]; // 当前网络是否可用 [ASIHTTPRequest isNetworkInUse]; // 当前网络是否为3G/2G [ASIHTTPRequest isNetworkReachableViaWWAN]; // 网络请求时,关闭状态栏上显示的loading [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO]; /********监听网络-NSNotificationCenter********/ [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; Reachability *internetReach = [[Reachability reachabilityForInternetConnection]]; [internetReach startNotifier]; NetworkStatus netStatus = [internetReach currentReachabilityStatus]; if (netStatus) { // NSLog(@"网络通"); } - (void)reachabilityChanged: (NSNotification* )note { NetworkStatus netStatus = [internetReach currentReachabilityStatus]; if (netStatus) { // NSLog(@"网络通"); }else { // NSLog(@"网络不通"); } } // 注意添加systemConfiguration框架;
原文地址:https://www.cnblogs.com/needly/p/3401031.html