1.iOS發(fā)送HTTP請求常用技術(shù)點
在iOS中,常見的發(fā)送HTTP請求的方案有
蘋果原生自帶
NSURLConnection
:用法簡單,最古老最經(jīng)典最直接的一種方案【坑比較多】
NSURLSession
:功能比NSURLConnection更加強大,蘋果目前比較推薦使用這種技術(shù)【2013推出,iOS7開始出的技術(shù)】
CFNetwork
:NSURL*的底層,純C語言第三方框架
ASIHttpRequest
:外號“HTTP終結(jié)者”,功能極其強大,可惜早已停止更新
AFNetworking
:簡單易用,提供了基本夠用的常用功能,維護和使用者多
MKNetworkKit
:簡單易用,產(chǎn)自三哥的故鄉(xiāng)印度,維護和使用者少
為了提高開發(fā)效率,企業(yè)開發(fā)用的基本是第三方框架,兼有對蘋果原生自帶技術(shù)的封裝
2.NSURLConnection
NSURL
:請求地址
NSURLRequest
:一個NSURLRequest對象就代表一個請求,它包含的信息有
一個NSURL對象
請求方法、請求頭、請求體
請求超時
… …
NSMutableURLRequest
:NSURLRequest的子類
NSURLConnection
: 負責(zé)發(fā)送請求,建立客戶端和服務(wù)器的連接;發(fā)送數(shù)據(jù)給服務(wù)器,并收集來自服務(wù)器的響應(yīng)數(shù)據(jù)
使用NSURLConnection發(fā)送請求的步驟:
1>創(chuàng)建一個NSURL對象,設(shè)置請求路徑
2>傳入NSURL創(chuàng)建一個NSURLRequest對象,設(shè)置請求頭和請求體
3>使用NSURLConnection發(fā)送請求
蘋果SDK提供的相關(guān)方法:
NSURLConnection常見的發(fā)送請求方法有以下幾種
//同步請求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
//異步請求:根據(jù)對服務(wù)器返回數(shù)據(jù)的處理方式的不同,又可以分為2種
//block回調(diào)
+ (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 的情況下,需要調(diào)用start方法開始發(fā)送請求
- (void)start;
- (void)cancel;//對應(yīng)終止發(fā)送請求
//成為NSURLConnection的代理,最好遵守 <NSURLConnectionDataDelegate> 協(xié)議
// NSURLConnectionDataDelegate協(xié)議中的代理方法
//開始接收到服務(wù)器的響應(yīng)時調(diào)用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
//接收到服務(wù)器返回的數(shù)據(jù)時調(diào)用(服務(wù)器返回的數(shù)據(jù)比較大時會調(diào)用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
//服務(wù)器返回的數(shù)據(jù)完全接收完畢后調(diào)用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
//請求出錯時調(diào)用(比如請求超時)
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
3.NSURLConnection使用
3.1發(fā)送同步請求
/**
* 發(fā)送同步請求
*/
- (void)sync{
// 0.請求路徑
NSURL *url = [NSURL URLWithString:@"http://www.lxweimin.com/users/468d1f0192cb/latest_articles"];
// 1.創(chuàng)建請求對象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2.發(fā)送請求
// sendSynchronousRequest阻塞式的方法,等待服務(wù)器返回數(shù)據(jù)
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
// 3.解析服務(wù)器返回的數(shù)據(jù)(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@ %@", string, response.allHeaderFields);
}
3.2發(fā)送異步請求
/**
* 發(fā)送異步請求
*/
- (void)async{
NSURL *url = [NSURL URLWithString:@"http://www.lxweimin.com/users/468d1f0192cb/latest_articles"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 請求完畢會來到這個block
// 解析服務(wù)器返回的數(shù)據(jù)(解析成字符串)
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;
NSLog(@"%zd %@", r.statusCode, r.allHeaderFields);
}];
}
3.3代理方式 <NSURLConnectionDataDelegate>
@interface ViewController () <NSURLConnectionDataDelegate>
/** 用來存放服務(wù)器返回的數(shù)據(jù) */
@property (nonatomic, strong) NSMutableData *responseData;
@end
@implementation ViewController
/**
* NSURLConnection 代理使用方式
*/
- (void)delegateAysnc{
NSURL *url = [NSURL URLWithString:@"http://www.lxweimin.com/users/468d1f0192cb/latest_articles"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
/**
* 接收到服務(wù)器的響應(yīng)
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse");
self.responseData = [NSMutableData data];
}
/**
* 接收到服務(wù)器的數(shù)據(jù)(如果數(shù)據(jù)量比較大,這個方法會被調(diào)用多次)
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// 不斷拼接服務(wù)器返回的數(shù)據(jù)
[self.responseData appendData:data];
NSLog(@"didReceiveData -- %zd", data.length);
}
/**
* 服務(wù)器的數(shù)據(jù)成功接收完畢
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"connectionDidFinishLoading");
NSString *string = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
self.responseData = nil;
}
/**
* 請求失敗(比如請求超時)
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError -- %@", error);
}
// didReceiveResponse
// didReceiveData -- 3752
// didReceiveData -- 12131
// didReceiveData -- 3052
// connectionDidFinishLoading
// 打印出的網(wǎng)頁代碼
// #pragma mark - <NSURLConnectionDataDelegate> -- end
@end
NSURL *url = [NSURL URLWithString:@"http://www.lxweimin.com/users/468d1f0192cb/latest_articles"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 1.自動發(fā)送請求
[NSURLConnection connectionWithRequest:request delegate:self];
// 2.自動發(fā)送請求
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// 3.1 手動發(fā)送請求
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn start];
// 3.2 取消發(fā)送請求
[conn cancel];
3.4異步線程執(zhí)行耗時操作,主線程更新UI
NSString *urlStr = @"http://www.lxweimin.com/users/468d1f0192cb/latest_articles";
NSURL *url = [NSURL URLWithString:urlStr];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// 回到主線程
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// 把網(wǎng)頁顯示在webView上
}];
}];
3.5GET請求多值參數(shù)
NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/weather?place=Beijing&place=Shanghai"];
//{"weathers":[{"city":"Beijing","status":"晴轉(zhuǎn)多云"},{"city":"Shanghai","status":"晴轉(zhuǎn)多云"}]}