首页 > 其他 > 详细

异步请求HTTP

时间:2014-10-09 00:06:47      阅读:311      评论:0      收藏:0      [点我收藏+]

代码:

@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

 

异步请求HTTP

原文:http://www.cnblogs.com/code-style/p/4011788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!