NSURLConnection
常用類:
NSURL:請求地址
NSURLRequest:一個NSURLRequest對象就代表一個請求,它包含的信息有
一個NSURL對象
請求方法、請求頭、請求體
請求超時
… …
NSMutableURLRequest:NSURLRequest的子類
NSURLConnection
負責發(fā)送請求,建立客戶端和服務器的連接
發(fā)送數(shù)據(jù)給服務器,并收集來自服務器的響應數(shù)據(jù)
使用NSURLConnection發(fā)送請求的步驟很簡單
創(chuàng)建一個NSURL對象,設置請求路徑
傳入NSURL創(chuàng)建一個NSURLRequest對象,設置請求頭和請求體
使用NSURLConnection發(fā)送請求
NSURLConnection常見的發(fā)送請求方法有以下幾種
同步請求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
異步請求:根據(jù)對服務器返回數(shù)據(jù)的處理方式的不同,又可以分為2種
block回調
+ (void)sendAsynchronousRequest:(NSURLRequest*) request? ? ? ? ? ? ? ? ? ? ? ? ? queue:(NSOperationQueue*) queue? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
代理
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate;
+ (NSURLConnection*)connectionWithRequest:(NSURLRequest *)request delegate:(id)delegate;
- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately;
在startImmediately = NO的情況下,需要調用start方法開始發(fā)送請求
- (void)start;
成為NSURLConnection的代理,最好遵守NSURLConnectionDataDelegate協(xié)議
NSURLConnectionDataDelegate協(xié)議中的代理方法
開始接收到服務器的響應時調用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
接收到服務器返回的數(shù)據(jù)時調用(服務器返回的數(shù)據(jù)比較大時會調用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
服務器返回的數(shù)據(jù)完全接收完畢后調用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
請求出錯時調用(比如請求超時)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
NSMutableURLRequest是NSURLRequest的子類,常用方法有
設置請求超時等待時間(超過這個時間就算超時,請求失?。?/p>
- (void)setTimeoutInterval:(NSTimeInterval)seconds;
設置請求方法(比如GET和POST)
- (void)setHTTPMethod:(NSString *)method;
設置請求體
- (void)setHTTPBody:(NSData *)data;
設置請求頭
- (void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
創(chuàng)建GET請求
NSString *urlStr = [@"http://120.25.226.186:32812/login?username=123&pwd=123" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
創(chuàng)建POST請求
NSString *urlStr = @"http://120.25.226.186:32812/login";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 請求體
NSString *bodyStr = @"username=123&pwd=123";
request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];