iOS 開發網絡篇——網絡請求(HTTP 協議)小結
1> 請求
* 客戶端 --> 服務器
* 請求的內容
a. 請求行(請求方法/HTTP 協議/請求資源路徑)
b. 請求頭(描述客戶端的信息)
c. 請求體(POST 請求才需要有,存放具體數據)
2> 響應
* 服務器 --> 客戶端
* 響應的內容
a. 狀態行(響應行、狀態碼)
b. 響應頭(服務器信息、返回數據的類型、返回數據的長度)
c. 實體內容(響應體、返回給客戶端的具體內容)
1> GET
* 參數都拼接在 URL 後面
* 參數有限制
2> POST
* 參數都在請求體
* 參數沒有限制
1> NSURLConnection
* 發送一個同步請求
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error;
* 發送一個異步請求
+ (void)sendAsynchronousRequest:(NSURLRequest*) request queue:(NSOperationQueue*) queue completionHandler:(void (^)(NSURLResponse* response, NSData* data, NSError* connectionError)) handler;
* 代理的方法(異步)
[NSURLConnection connectionWithRequest:request delegate:self];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conn start];
整體來看,HTTP 通訊就是「客戶端發請求、伺服器回應」的過程;請求由請求行、請求頭與請求體組成,回應則由狀態行、回應頭與實體內容組成。而在 iOS 端,NSURLConnection 提供了同步、異步(block 回調)以及代理三種發送方式,可依場景需求靈活選用。