• 【转】iOS网络请求


    1、creating requests
    request分为同步和异步两种。不同之处在于开始request的函数:
    [request startSynchronous];
    [request startAsynchronous];
    其中,异步的request构造方式如下:
    - (void) grabURLs
    {
        NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];//url需要添加http://
        ASIHTTPRequest *request;
        //for (int i = 0; i < 5; i++) {
            request = [ASIHTTPRequest requestWithURL:url];
            [request setDelegate:self];
          //  if (_queue == nil) {
            //    _queue = [[NSOperationQueue alloc] init];
           // }else
           //       [_queue cancelAllOperations];
          //  request.userInfo = [NSString stringWithFormat:@"the index is %d",i];
            //request.tag = i;
            //[_queue addOperation:request];
            [request startAsynchronous];
        }
    }

    - (void)requestFinished:(ASIHTTPRequest *)request
    {
        // Use when fetching text data
        NSString *responseString = [request responseString];
        //NSLog(@"the content is %@.",responseString);
        if (request.tag == 4) {
            NSLog(@"lskdffj.");
        }
    }

    - (void)requestFailed:(ASIHTTPRequest *)request
    {
        NSError *error = [request error];
        NSLog(@"the error is %@.",error);
    }
    在异步的request中,还可以通过下面的代码实现采用自己的函数执行成功和失败的操作:

    [request setDelegate:self]
    [
    request setDidFinishSelector:@selector(requestDone:)];
    [request setDidFailSelector:@selector(requestWentWrong:)]


    如上面例子所示:我还可以创建一个NSOperationQueue,用于控制多个request的进程。当然可以采用更专业的ASINetworkQueues。
    注:针对多个request调用相同的函数进行成功和失败的处理函数,但是还需要对各个request区别对待的场合,可以通过设置request的tag值或userInfo来区分。
    2、ASINetworkQueues
    (1)使用ASINetworkQueues和NSOperationQueue的不同之处在于,调用[queue go];才会真正的运行。
    (2)同一个queue中的request,若有一个fail的话,后面的requests都会被cancel,修改方法为:
    [queue setShouldCancelAllRequestsOnFailure:NO];
    3、cancel 异步requests
    (1)注:仅有异步的request才能被取消,同步的是取消不了的。
    [request cancel];
    或者[request clearDelegatesAndCancel];
    对一个ASINetworkQueues对象可以通过[queue cancelAllOperations];实现。
    (2)由于setDelegate函数,对与delegate并没有retain的操作,所以需要注意在delegate释放的时候,记得将request和queue的delegate设置为nil,并且取消对应的requests。
    4、ASIFormDataRequest
    - (void) loginAction
    {
        NSString *userName = self.username.text;
        NSString *passWord = self.password.text;
        NSLog(@"username:%@, password:%@",userName,passWord);
        NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8000/books/login/"];
        //NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/"];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        [request addPostValue:userName forKey:@"username"];//setPostValue:forKey:
        [request addPostValue:passWord forKey:@"password"];//setPostValue:forKey:
       
        [request startSynchronous];
        NSError *error = [request error];
        if (!error) {
            NSString *response = [request responseString];
            NSLog(@"the data received is %@",response);
        }else {
            NSLog(@"error accured. %@",error);      
        }
    }
    同时还可以通过ASIFormDataRequest来实现文件上传,它可以自动的读取磁盘上的文件然后上传。
    [request setFile:@"/Users/ben/Desktop/1.jpg" forKey:@"photo"];
    5、下载数据
    如果通过request获得的数据量非常大,可以通过函数将获得的数据直接存入磁盘上的一个文件内。
    - (void) grabURLs
    {
        NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
        ASIHTTPRequest *request;
        for (int i = 0; i < 5; i++) {
            request = [ASIHTTPRequest requestWithURL:url];
            [request setDelegate:self];
            if (_queue == nil) {
                _queue = [[NSOperationQueue alloc] init];
            }
            request.userInfo = [NSString stringWithFormat:@"the index is %d",i];
            request.tag = i;
            NSString *filename = [NSString stringWithFormat:@"/Users/wukuniqiang/Desktop/%d.html",i];
            [request setDownloadDestinationPath:filename];
            [_queue addOperation:request];
            //[request[i] startAsynchronous];
        }
    }
    (本来想下载mp3的,但是校园网速度不给力,等了好久没反应,就变成个网页了)
    下载进度的显示方法有两种:simple progress和 accurate progress
    针对第一种,uiprogressview仅仅更新两次,0和100%
    针对第二种,uiprogressview则随时更新。所以针对大文件的下载,推荐使用第二种方法。
    request.showAccurateProgress = YES;
    6、断点续传
    断点续传需要做以下三步操作:
    (1)设置下载的文件的位置
    [request setDownloadDestinationPath:@"filename.txt.download"]
    (3)设置采用断点续传
    [request setAllowResumeForFileDownloads:YES];
    7、基于流上传本地大文件
    可以采用的方法有两种:
    (1)ASIFormDataRequest的函数[request setFile: forKey:];
    (2)ASIHTTPRequst的函数[request appendPostDataFromFile:@"/*/filename"];
    ASIHTTPRequest中调用上诉函数之前,首先应该设置[request setShouldStreamPostDataFromDisk:YES];
    注:上面两种方法不可混用
    8、use a download cache
    下面三种情况的时候需要采用download cache
    1、当前没有网络连接并且不能再次下载
    2、再次请求的数据和上次获得的数据有变化的时候
    3、请求的数据永远不会变化,仅仅需要下载一次,以后可以放心使用的数据

    ASIDownloadCache 设置下载缓存

    它对Get请求的响应数据进行缓存(被缓存的数据必需是成功的200请求):

    采用ASIHTTPRequest的类方法,对所有的request设置downloadcache:

    [ASIHTTPRequest setDownloadCache:[ASIDownloadCache sharedCache]];

    当设置缓存策略后,所有的请求都被自动的缓存起来。

    另外,如果仅仅希望某次请求使用缓存操作,也可以这样使用:

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDownloadCache:[ASIDownloadCache sharedCache]];
    多种的缓存并存

    仅仅需要创建不同的ASIDownloadCache,并设置缓存所使用的路径,并设置到需要使用的request实例中:

    ASIDownloadCache *cache = [[[ASIDownloadCache alloc] init] autorelease];
    [cache setStoragePath:@"/Users/ben/Documents/Cached-Downloads"];
    [self setMyCache:cache];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDownloadCache:[self myCache]];
  • 相关阅读:
    四、java IO--使用字节流拷贝文件
    三、java IO--使用字节流写入文件
    二、java IO--使用字节流读取文件
    一、java--IO概念
    xml解析/读取--dom4j
    java程序执行顺序
    Flask学习——cookie操作
    Linux13 shell函数、数组及awk、awk中的数组
    Linux12 RPM 和yum的使用
    Linux11 IP网段划分及主机接入网络
  • 原文地址:https://www.cnblogs.com/lixiong-iOS/p/3665984.html
Copyright © 2020-2023  润新知