iOS总结:ASIHttpRequest类库发送请求(同步请求和异步请求)

1.发送异步请求

 

1)在.h中导入头文件

 

#import "ASIHTTPRequest.h"

 

2)设置代理

ASIHTTPRequestDelegate

 

3)URL —-> 发请求 —> 设置代理 —> 开始异步请求

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.backgroundColor = [UIColor whiteColor];

    //异步请求

    //url

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

    //发请求

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    //代理

    request.delegate = self;

    //开始

    [request startAsynchronous];

    [self.window makeKeyAndVisible];

    return YES;

}

 

3)若获取返回的文本信息,调用responseString方法,

   若获取的是二进制文件,如:图片、MP3文件,则调用NSData方法,获取一个NSData对象

-(void)requestFinished:(ASIHTTPRequest *)request

{

    NSString *response = [request responseString];

    NSLog(@"%@", response);

    NSData *data = [request responseData];

    NSLog(@"%@", data);

}

 

-(void)requestFailed:(ASIHTTPRequest *)request

{

    NSError *error = [request error];

    NSLog(@"%@", error);

}

 

输出结果:

文本信息为

二进制信息为

 

 2.同步请求(和异步请求类似)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.window.backgroundColor = [UIColor whiteColor];

    //同步请求

    //url

    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];

    //发请求

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

    //代理

    request.delegate = self;

    //开始

    [request startSynchronous];

    NSError *error = [request error];

    if (!error) {

        NSString *response = [request responseString];

        NSLog(@"%@", response);

    }

    [self.window makeKeyAndVisible];

    return YES;

}

  一般情况下,应该优先使用异步请求,当在主线程中使用ASIHTTPRequest同步请求,应用程序的界面会锁定,无法进行任何操作,直到请求完成。

posted @ 2015-11-07 16:44  11月的淡然  阅读(164)  评论(0编辑  收藏  举报