HTTP要求標頭

來源:互聯網
上載者:User
http://www.php.cn/code/10550.html" target="_blank">用戶端使用服務端API介面時,需構造HTTP要求標頭,一般情況下是初始化一個NSMutableURLRequest,然後佈建要求方法、請求體,要求標頭,如下:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];    [request setHTTPMethod:@"POST"];    [request setHTTPBody:bodyData];    [request setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"];    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)bodyData.length] forHTTPHeaderField:@"Content-Length"];    [request setValue:authorization forHTTPHeaderField:@"Authorization"];

猿題庫的網路請求(YTKNetwork)已把要求方法、請求體,要求標頭等封裝好允許使用者重載進行自訂。包括:

#pragma mark - Subclass Override///=============================================================================/// @name Subclass Override///=============================================================================///  Called on background thread after request succeded but before switching to main thread. Note if///  cache is loaded, this method WILL be called on the main thread, just like `requestCompleteFilter`.- (void)requestCompletePreprocessor;///  Called on the main thread after request succeeded.- (void)requestCompleteFilter;///  Called on background thread after request succeded but before switching to main thread. See also///  `requestCompletePreprocessor`.- (void)requestFailedPreprocessor;///  Called on the main thread when request failed.- (void)requestFailedFilter;///  The baseURL of request. This should only contain the host part of URL, e.g., http://www.example.com.///  See also `requestUrl`- (NSString *)baseUrl;///  The URL path of request. This should only contain the path part of URL, e.g., /v1/user. See alse `baseUrl`.//////  @discussion This will be concated with `baseUrl` using [NSURL URLWithString:relativeToURL].///              Because of this, it is recommended that the usage should stick to rules stated above.///              Otherwise the result URL may not be correctly formed. See also `URLString:relativeToURL`///              for more information.//////              Additionaly, if `requestUrl` itself is a valid URL, it will be used as the result URL and///              `baseUrl` will be ignored.- (NSString *)requestUrl;///  Optional CDN URL for request.- (NSString *)cdnUrl;///  Requset timeout interval. Default is 60s.//////  @discussion When using `resumableDownloadPath`(NSURLSessionDownloadTask), the session seems to completely ignore///              `timeoutInterval` property of `NSURLRequest`. One effective way to set timeout would be using///              `timeoutIntervalForResource` of `NSURLSessionConfiguration`.- (NSTimeInterval)requestTimeoutInterval;///  Additional request argument.- (nullable id)requestArgument;///  Override this method to filter requests with certain arguments when caching.- (id)cacheFileNameFilterForRequestArgument:(id)argument;///  HTTP request method.- (YTKRequestMethod)requestMethod;///  Request serializer type.- (YTKRequestSerializerType)requestSerializerType;///  Response serializer type. See also `responseObject`.- (YTKResponseSerializerType)responseSerializerType;///  Username and password used for HTTP authorization. Should be formed as @[@"Username", @"Password"].- (nullable NSArray<NSString *> *)requestAuthorizationHeaderFieldArray;///  Additional HTTP request header field.- (nullable NSDictionary<NSString *, NSString *> *)requestHeaderFieldValueDictionary;///  Use this to build custom request. If this method return non-nil value, `requestUrl`, `requestTimeoutInterval`,///  `requestArgument`, `allowsCellularAccess`, `requestMethod` and `requestSerializerType` will all be ignored.- (nullable NSURLRequest *)buildCustomUrlRequest;///  Should use CDN when sending request.- (BOOL)useCDN;///  Whether the request is allowed to use the cellular radio (if present). Default is YES.- (BOOL)allowsCellularAccess;///  The validator will be used to test if `responseJSONObject` is correctly formed.- (nullable id)jsonValidator;///  This validator will be used to test if `responseStatusCode` is valid.- (BOOL)statusCodeValidator;

要求標頭通過重寫方法- (NSDictionary *)requestHeaderFieldValueDictionary;返回一個字典,然後在方法
- (AFHTTPRequestSerializer *)requestSerializerForRequest:(YTKBaseRequest *)request;中將網路請求序列化,供構造NSURLSessionTask使用。

- (NSDictionary *)requestHeaderFieldValueDictionary {    NSString *paraUrlString = AFQueryStringFromParameters([self requestArgument]);    NSString *authorization =[[YTKNetworkConfig sharedConfig] getAuthorization:[self requestUrl]];    return @{@"Accept-Encoding":@"gzip, deflate",             @"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8",             @"Content-Length":[NSString stringWithFormat:@"%lu", (unsigned long)paraUrlString.length],             @"Authorization":authorization};}

下面具體說說要求標頭裡幾個欄位的含義:

Accept-Encoding

  • 表示本地可以接收壓縮格式的資料,而伺服器在處理時就將大檔案壓縮再發回用戶端。用戶端接收完成後在本地對資料進行解壓操作。

  • gzip:用於UNⅨ系統的檔案壓縮,HTTP協議上的gzip編碼是一種用來改進WEB應用程式效能的技術。大流量的WEB網站常常使用gzip讓使用者感受更快的速度。這一般是指WWW伺服器中安裝的一個功能,當有人來訪問這個伺服器中的網站時,伺服器中的這個功能就將網頁內容壓縮後傳輸到來訪的電腦瀏覽器中顯示出來。一般對純文字內容可壓縮到原大小的40%,從而使得資料轉送速度加快。當然這也會增加伺服器的負載,一般伺服器中都安裝有這個功能模組的。

  • deflate:一種使用LZ77演算法與哈夫曼編碼(Huffman Coding)的一個無損資料壓縮無專利演算法的壓縮技術。

  • HTTP內容編碼和HTTP壓縮的區別:在HTTP協議中,可以對內容(也就是body部分)進行編碼, 可以採用gzip這樣的編碼。 從而達到壓縮的目的。 也可以使用其他的編碼把內容攪亂或加密,以此來防止未授權的第三方看到文檔的內容。所以我們說HTTP壓縮,其實就是HTTP內容編碼的一種。

  • HTTP壓縮的過程:
    1、用戶端發送Http request 給Web伺服器, request 中有Accept-Encoding: gzip, deflate。 (告訴伺服器, 瀏覽器支援gzip壓縮)。
    2、伺服器接到request後, 產生原始的Response, 其中有原始的Content-Type和Content-Length。
    3、伺服器通過gzip,來對Response進行編碼, 編碼後header中有Content-Type和Content-Length(壓縮後的大小), 並且增加了Content-Encoding:gzip. 然後把Response發送給用戶端。
    4、用戶端接到Response後,根據Content-Encoding:gzip來對Response 進行解碼。 擷取到原始response後, 然後處理資料的顯示。

  • 其它:compress表明實體採用Unix的檔案壓縮程式;identity表明沒有對實體進行編碼。當沒有Content-Encoding header時, 就預設為這種情況。gzip, compress, 以及deflate編碼都是無損壓縮演算法,用於減少傳輸報文的大小,不會導致資訊損失。 其中gzip通常效率最高, 使用最為廣泛。

Content-Type

  • 表示內容類型,一般是指用戶端存在的Content-Type,用於定義網路檔案的類型和網頁的編碼,決定用戶端將以什麼形式、什麼編碼讀取這個檔案。即用於標識發送或接收到的資料的類型,用戶端根據該參數來決定資料的開啟檔案。

  • application/x-www-form-urlencoded:資料被編碼為成對的名稱和數值,這是標準的編碼格式;multipart/form-data: 表單資料被編碼為一條訊息,頁上的每個控制項對應訊息中的一個部分。 text/plain: 表單資料以純文字形式進行編碼,其中不含任何控制項或格式字元。
    1、當action為get時候,瀏覽器用x-www-form-urlencoded的編碼方式把form資料轉換成一個字串(name1=value1&name2=value2…),然後把這個字串append到url後面,用?分割,載入這個新的url。
    2、當action為post時候,瀏覽器把form資料封裝到http body中,然後發送到server。 如果沒有type=file的控制項,用預設的application/x-www-form-urlencoded就可以了。 但是如果有type=file的話,就要用到multipart/form-data了。瀏覽器會把整個表單以控制項為單位分割,並為每個部分加上Content-Disposition(form-data或者file),Content-Type(預設為text/plain),name(控制項name)等資訊,並加上分割符(boundary)。

Content-Length

  • 表示述HTTP訊息實體的傳輸長度。訊息實體長度:即Entity-length,壓縮之前的message-body的長度;
    訊息實體的傳輸長度:Content-length,壓縮後的message-body的長度。(參數拼接成的字典)

Authorization

  • HTTP基本認證是一種用來允許Web瀏覽器,或其他用戶端程式在請求時提供以使用者名稱和口令形式的憑證的登入方式。授權機制根據服務端定的規則確定。

  • 認證 (authentication) 和授權 (authorization) 的區別:你要登機,你需要出示你的身份證和機票,身份證是為了證明你張三確實是你張三,這就是 authentication;而機票是為了證明你張三確實買了票可以上飛機,這就是 authorization。 你要登陸論壇,輸入使用者名稱張三,密碼1234,密碼正確,證明你張三確實是張三,這就是 authentication;再一check使用者張三是個版主,所以有許可權加精刪別人帖,這就是 authorization。

POST與GET區別

  • 站在HTML角度:
    1、GET在瀏覽器回退時是無害的,而POST會再次提交請求。
    2、GET產生的URL地址可以被Bookmark,而POST不可以。
    3、GET請求會被瀏覽器主動cache,而POST不會,除非手動設定。
    4、GET請求只能進行url編碼,而POST支援多種編碼方式。
    5、GET請求參數會被完整保留在瀏覽器記錄裡,而POST中的參數不會被保留。
    6、GET請求在URL中傳送的參數是有長度限制的,而POST麼有。
    7、對參數的資料類型,GET只接受ASCII字元,而POST沒有限制。
    8、GET比POST更不安全,因為參數直接暴露在URL上,所以不能用來傳遞敏感資訊。
    9、GET參數通過URL傳遞,POST放在Request body中。

  • 站在HTTP的角度:
    1、HTTP是基於TCP/IP的關於資料如何在全球資訊網中如何通訊的協議。HTTP的底層是TCP/IP。所以GET和POST的底層也是TCP/IP,也就是說,GET/POST都是TCP連結。GET和POST能做的事情是一樣一樣的。你要給GET加上request body,給POST帶上url參數,技術上是完全行的通的。HTTP只是個管理辦法,而TCP才是GET和POST怎麼實現的基本。
    2、HTTP沒有要求,如果Method是POST資料就要放在BODY中。也沒有要求,如果Method是GET,資料(參數)就一定要放在URL中而不能放在BODY中。也就是說,GET和POST與資料如何傳遞沒有關係。HTTP協議對GET和POST都沒有對長度的限制。安全不安全和GET、POST沒有關係。
    3、GET產生一個TCP資料包;POST產生兩個TCP資料包。對於GET方式的請求,瀏覽器會把http header和data一併發送出去,伺服器響應200(返回資料);而對於POST,瀏覽器先發送header,伺服器響應100 continue,瀏覽器再發送data,伺服器響應200 ok(返回資料)。

HTTP狀態代碼大全

1、1** 資訊,伺服器收到請求,需要要求者繼續執行操作
2、2** 成功,操作被成功接收並處理
3、3** 重新導向,需要進一步的操作以完成請求
4、4** 用戶端錯誤,請求包含語法錯誤或無法完成請求
5、5** 伺服器錯誤,伺服器在處理請求的過程中發生了錯誤

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.