• HTTP NSURLConnection


    LINK URL: http://qzc770707.blog.163.com/blog/static/3408275320105249566560/

    通常在iPhone里用NSURLConnection做url请求

    1.NSURLConnection同步与异步请求
    (1)异步请求:
    NSMutableData* buf = [[NSMutableData alloc] initWithLength:0];
    NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
     
    // 收到响应时, 会触发
    - (void)connection:(NSURLConnection *)aConnection didReceiveResponse:(NSURLResponse *)aResponse;
    // 可以在里面判断返回结果, 或者处理返回的http头中的信息
     
    // 每收到一次数据, 会调用一次
    - (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data;
    // 因此一般来说,是
    - (void)connection:(NSURLConnection *)aConn didReceiveData:(NSData *)data
    {
        [buf appendData:data];
    }
    // buffer就是前面initWithRequest时同时声明的.
     
    // 网络错误时触发
    - (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error;
     
    // 全部数据接收完毕时触发
    - (void)connectionDidFinishLoading:(NSURLConnection *)aConn;


    (2)同步请求:
    / 初始化請求
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];         
    // 設置URL
            [request setURL:[NSURL URLWithString:urlStr]];
    // 設置HTTP方法
            [request setHTTPMethod:@"GET"];
    // 發送同步請求, 這裡得returnData就是返回得數據楽
            NSData *returnData = [NSURLConnection sendSynchronousRequest:request 
                                                       returningResponse:nil error:nil]; 
    // 釋放對象
            [request release];

    2. 注意head请求,如果在head响应中继续请求下一个地址,之后的响应和前一个响应对象的指针地址一样,内容也一样。改为了get请求,解决此问题。还没有更彻底的解决办法。

       另外设置setCachePolicy不起作用。

    3.ASIHTTPRequest.

       ASIHTTPRequest不是直接使用的NSURLConnection.

       http://www.cnblogs.com/chen1987lei/archive/2011/06/07/2074636.html

       http://blog.csdn.net/kmyhy/archive/2011/06/03/6524916.aspx

       http://allseeing-i.com/

       队列异步请求中中获取或识别不同request小技巧 
    a,可以设置一个上下文(userInfo)到request对象中,当请求响应完后可以通过访问request对象的userInfo获取里面的信息
    b,为每一个请求实例设置不同的setDidFinishSelector / setDidFailSelector的回调方法
    c,子类化ASIHTTPRequest,重写requestFinished: 与 failWithProblem:方法

       安全的内存回收建议 
    request并没有retain delegate,所以若在没有请求完时候释放此delegate,需要在dealloc方法里先取消所有请求,再释放请求实例,如- (void)dealloc{ [request clearDelegatesAndCancel]; [request release]; ...[super dealloc];}

  • 相关阅读:
    Python 内置函数 —— format
    命名集 —— 名字结构
    命名集 —— 名字结构
    存储与主板的外设接口
    存储与主板的外设接口
    验证码的认识
    验证码的认识
    windows 路径
    windows 路径
    极限的求法
  • 原文地址:https://www.cnblogs.com/xingchen/p/2091682.html
Copyright © 2020-2023  润新知