擷取HTTP狀態代碼
ASIHTTPRequest並不對HTTP狀態代碼做任何處理(除了重新導向和授權狀態代碼,下面會介紹到),所以你必須自己檢查狀態值並正確處理。
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request startSynchronous];int statusCode = [request responseStatusCode];NSString *statusMessage = [request responseStatusMessage];
讀取回應標頭
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];[request startSynchronous];NSString *poweredBy = [[request responseHeaders] objectForKey:@"X-Powered-By"];NSString *contentType = [[request responseHeaders] objectForKey:@"Content-Type"];
處理文本編碼
ASIHTTPRequest會試圖讀取返回資料的編碼資訊(Content-Type頭資訊)。如果它發現了編碼資訊,它會將編碼資訊設定為合適的 NSStringEncoding.如果它沒有找到編碼資訊,它會將編碼設定為預設編碼(NSISOLatin1StringEncoding)。
當你調用[request responseString],ASIHTTPRequest會嘗試以responseEncoding將返回的Data轉換為NSString。
處理重新導向
當遇到以下HTTP狀態代碼之一時,ASIHTTPRequest會自動重新導向到新的URL:
- 301 Moved Permanently
- 302 Found
- 303 See Other
當發生重新導向時,響應資料的值(responseHeaders,responseCookies,responseData,responseString等等)將會映射為最終地址的相應返回資料。
當URL發生迴圈重新導向時,設定在這個URL上的cookie將被儲存到全域域中,並在適當的時候隨重新導向的請求發送到伺服器。
Cookies set on any of the urls encountered during a redirection cycle will be stored in the global cookie store, and will be represented to the server on the redirected request when appropriate.
你可以關閉自動重新導向:將shouldRedirect設定為NO。
預設情況下,自動重新導向會使用GET請求(請求體為空白)。這種行為符合大多數瀏覽器的行為,但是HTTP spec規定301和302重新導向必須使用原有方法。
要對301、302重新導向使用原方法(包含請求體),在發起請求之前,設定shouldUseRFC2616RedirectBehaviour 為YES。