NSURLConnection是負責發(fā)送請求瓦胎,建立客戶端和服務(wù)器的連接芬萍。發(fā)送數(shù)據(jù)給服務(wù)器尤揣,并接受來自服務(wù)器的響應(yīng)數(shù)據(jù)。
使用NSURLConnection發(fā)送請求的分3步
(1)創(chuàng)建一個NSURL對象担忧,設(shè)置請求路徑
(2)傳入NSURL創(chuàng)建一個NSURLRequest對象芹缔,設(shè)置請求頭和請求體,請求超時...(創(chuàng)建請求對象)
(3)使用NSURLConnection發(fā)送NSURLRequest(發(fā)送請求)
NSURLConnection提供了兩種發(fā)送網(wǎng)絡(luò)請求的方法瓶盛,分別是
1最欠、同步請求,返回data數(shù)據(jù)惩猫,會卡主UI主線程芝硬。
+ (nullable NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse * __nullable * __nullable)response error:(NSError **)error;
2、異步請求轧房,數(shù)據(jù)通過block返回拌阴,不卡主線程。
+ (void)sendAsynchronousRequest:(NSURLRequest*) request
queue:(NSOperationQueue*) queue
completionHandler:(void (^)(NSURLResponse* __nullable response, NSData* __nullable data, NSError* __nullable connectionError)) handler;
3奶镶、對應(yīng)代碼
// 創(chuàng)建一個URL :請求路徑
NSString *urlStr = [NSString stringWithFormat:@"http://xxx.com"];
NSURL *url = [NSURL URLWithString:urlStr];
// 創(chuàng)建一個請求迟赃,默認為GET請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 發(fā)送一個同步請求(在主線程發(fā)送請求)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
一個簡單的NSURLConnection的同步請求的demo。請點擊這里