iOS網(wǎng)絡(luò)基礎(chǔ) - iOS網(wǎng)絡(luò)基礎(chǔ)
iOS網(wǎng)絡(luò)基礎(chǔ)
創(chuàng)建請(qǐng)求-NSURLRequest
客戶端發(fā)起請(qǐng)求-NSURLConnection
接收服務(wù)器端的響應(yīng)-NSURLConnectionDataDelegate
從服務(wù)器端的響應(yīng)中獲取數(shù)據(jù)
NSURLRequest
@interface NSURLRequest : NSObject
@property (copy) NSString *HTTPMethod;
@property (nullable, readonly, copy) NSData *HTTPBody;
@property (nullable, readonly, copy) NSDictionary<NSString *, NSString *> *allHTTPHeaderFields;
上面提到的這些屬性都是只讀的廷支。因此我們應(yīng)使用NSMutableURLRequest
@interface NSMutableURLRequest : NSURLRequest
@property (copy) NSString *HTTPMethod;
@property (nullable, copy) NSData *HTTPBody;
@property (nullable, copy) NSDictionary<NSString *, NSString *> *allHTTPHeaderFields;
默認(rèn)情況下創(chuàng)建的http請(qǐng)求方法就是get呻疹∽圆祝可以通過屬性HTTPMethod指定方法。通過屬性allHTTPHeaderFields修改header剃法。
NSURLConnection
- (nullable instancetype)initWithRequest:(NSURLRequest *)request delegate:(nullable id)delegate startImmediately:(BOOL)startImmediately
NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
接收響應(yīng)-->接收數(shù)據(jù)-->響應(yīng)接收完畢
NSURLResponse
數(shù)據(jù)解析 - NSJSONSerialization :NSObject
將NSData轉(zhuǎn)成JSON
將JSON轉(zhuǎn)成NSData
App Transport Security
- 不允許明文的HTTP請(qǐng)求
- 默認(rèn)使用HTTPS庭瑰,鼓勵(lì)采用HTTPS帶來更好的安全性
- 通過info.plist進(jìn)行配置
HTTPS
相當(dāng)于將明文的HTTP協(xié)議加密号醉。
http:// 默認(rèn)端口:80
https:// 默認(rèn)端口:443
- 超文本傳輸安全協(xié)議
- http over TLS
- TLS:傳輸層安全協(xié)議(Transport Layer Security)
為應(yīng)用帶來的好處:
- 加密(Encryption)
- 完整性 (Integrity)
- 認(rèn)證 (Authentication)
NSURLConnection流程
NSURLSession
- 替代NSURLConnection
- iOS 7+
- 2013年wwdc上推出
NSURLSession
- 創(chuàng)建一個(gè)請(qǐng)求
- 客戶端發(fā)起請(qǐng)求
- 接收服務(wù)器端的響應(yīng)
- 從服務(wù)器的響應(yīng)中獲取數(shù)據(jù)
NSURLSession的實(shí)現(xiàn)
NSURLSession工作流程
[TOC]