iOS總結:ASIHttpRequest類庫發送請求(同步請求和非同步請求)

來源:互聯網
上載者:User

標籤:

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同步請求,應用程式的介面會鎖定,無法進行任何操作,直到請求完成。

iOS總結:ASIHttpRequest類庫發送請求(同步請求和非同步請求)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.