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

  • 相关阅读:
    Python抓取网页动态数据——selenium webdriver的使用
    mac上vim插件YouCompleteMe的安装
    shell命令的搜索顺序(hash -r, hash的作用)
    mac gcc framework include
    一个debug了4个多小时的bug, 操作系统真象还原: 试图运行起第6章的print相关函数却没有预期效果
    python中bytes类型与str类型的区别以及python中str类型是怎么存储的
    一行不解的awk代码
    OKR案例——不同类型的OKR实例
    PostgreSQL与MySQL优势比较
    [Win7 x64]Eclipse Indigo 3.7 中文字体偏小解决方案: Consolas 微软雅黑混合字体!
  • 原文地址:https://www.cnblogs.com/iosdanran/p/4945646.html
Copyright © 2011-2022 走看看