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

 

你可能感兴趣的:(http)