• 异步请求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

  • 相关阅读:
    一只iPhone的全球之旅
    iOS开发之在地图上绘制出你运行的轨迹
    iOS开发之一些字符串常用的代码
    json格式化和查看工具
    iOS开发之结合asp.net webservice实现文件上传下载
    更改GROOVE的文件夹位置
    调试Windows Service
    从数据库中获取Insert语句
    iOS开发学习笔记(一)
    《影响力》的影响
  • 原文地址:https://www.cnblogs.com/code-style/p/4011788.html
Copyright © 2020-2023  润新知