標籤:
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類庫發送請求(同步請求和非同步請求)