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同步请求,应用程序的界面会锁定,无法进行任何操作,直到请求完成。

转载于:https://www.cnblogs.com/iosdanran/p/4945646.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值