zoukankan      html  css  js  c++  java
  • 异步请求HTTP

    代码:

    @interface HttpProcessor : NSObject <NSURLConnectionDataDelegate>
    {
        NSMutableData *buffer;
    }
    
    @property BOOL finished;
    @property (strong, nonatomic) NSString *html;
    @end
    
    @implementation HttpProcessor
    @synthesize finished;
    @synthesize html;
    
    -(id)init
    {
        if (self) {
            finished = NO;
        }
        
        return self;
    }
    
    // 开始接收响应
    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        finished = NO;
        buffer = [[NSMutableData alloc] init];
    }
    
    // 接收ing , 可能多次调用
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
    {
        [buffer appendData:data];
    }
    
    // 结束响应
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection
    {
        finished = YES;
        html = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
        //NSLog(@"%@", html);
        NSLog(@"OK");
    }
    @end
    
    void request(NSString *urlString)
    {
        NSLog(@"BEGIN");
        // make request object
        NSURL *url = [[NSURL alloc]initWithString:urlString];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
        [request setHTTPMethod:@"GET"];
        [request setTimeoutInterval:10];
        
        // send request
        HttpProcessor *processor = [[HttpProcessor alloc]init];
        [NSURLConnection connectionWithRequest:request delegate:processor];
    }

     代码块:

    void request(NSString *urlString)
    {
        NSLog(@"BEGIN");
        // make request object
        NSURL *url = [[NSURL alloc]initWithString:urlString];
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url];
        [request setHTTPMethod:@"GET"];
        [request setTimeoutInterval:10];
        // send request
        [NSURLConnection
         sendAsynchronousRequest:request
         queue:[NSOperationQueue mainQueue]
         completionHandler:
            ^(NSURLResponse *response, NSData *result, NSError *error)
            {
                //只会进入一次,方法内部已经实现了Buffer作用
                NSString *html = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
                NSLog(@"html = %@", html);
            }
         
         ];
    }

    参考:

    http://www.tuicool.com/articles/2Yru6f

  • 相关阅读:
    [bzoj1731] [Usaco2005 dec]Layout 排队布局
    [bzoj1914] [Usaco2010 OPen]Triangle Counting 数三角形
    [bzoj1774] [Usaco2009 Dec]Toll 过路费
    [bzoj1783] [Usaco2010 Jan]Taking Turns
    [bzoj1705] [Usaco2007 Nov]Telephone Wire 架设电话线
    [bzoj1700]: [Usaco2007 Jan]Problem Solving 解题
    定时启动任务
    数据库表转javaBean
    验证码的生成
    MD5加密与验证
  • 原文地址:https://www.cnblogs.com/code-style/p/4011788.html
Copyright © 2011-2022 走看看