HTTP 常見的狀態(tài)碼有哪些?
HTTP 狀態(tài)碼用于描述 HTTP 請(qǐng)求的結(jié)果,比如2xx 就代表請(qǐng)求被成功處理。

1xx Informational(信息性狀態(tài)碼)
相比于其他類別狀態(tài)碼來說,1xx 你平時(shí)你大概率不會(huì)碰到,所以這里直接跳過。
2xx Success(成功狀態(tài)碼)
200 OK :請(qǐng)求被成功處理。比如我們發(fā)送一個(gè)查詢用戶數(shù)據(jù)的HTTP 請(qǐng)求到服務(wù)端,服務(wù)端正確返回了用戶數(shù)據(jù)。這個(gè)是我們平時(shí)最常見的一個(gè) HTTP 狀態(tài)碼。 201 Created :請(qǐng)求被成功處理并且在服務(wù)端創(chuàng)建了一個(gè)新的資源。比如我們通過 POST 請(qǐng)求創(chuàng)建一個(gè)新的用戶。 202 Accepted :服務(wù)端已經(jīng)接收到了請(qǐng)求,但是還未處理。 204 No Content :服務(wù)端已經(jīng)成功處理了請(qǐng)求,但是沒有返回任何內(nèi)容。
這里格外提一下 204 狀態(tài)碼,平時(shí)學(xué)習(xí)/工作中見到的次數(shù)并不多。
HTTP RFC 2616對(duì)204狀態(tài)碼的描述如下:
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
簡(jiǎn)單來說,204狀態(tài)碼描述的是我們向服務(wù)端發(fā)送 HTTP 請(qǐng)求之后,只關(guān)注處理結(jié)果是否成功的場(chǎng)景。也就是說我們需要的就是一個(gè)結(jié)果:true/false。
舉個(gè)例子:你要追一個(gè)女孩子,你問女孩子:“我能追你嗎?”,女孩子回答:“好!”。我們把這個(gè)女孩子當(dāng)做是服務(wù)端就很好理解 204 狀態(tài)碼了。
3xx Redirection(重定向狀態(tài)碼)
301 Moved Permanently :資源被永久重定向了。比如你的網(wǎng)站的網(wǎng)址更換了。 302 Found :資源被臨時(shí)重定向了。比如你的網(wǎng)站的某些資源被暫時(shí)轉(zhuǎn)移到另外一個(gè)網(wǎng)址。
4xx Client Error(客戶端錯(cuò)誤狀態(tài)碼)
400 Bad Request :發(fā)送的HTTP請(qǐng)求存在問題。比如請(qǐng)求參數(shù)不合法、請(qǐng)求方法錯(cuò)誤。 401 Unauthorized :未認(rèn)證卻請(qǐng)求需要認(rèn)證之后才能訪問的資源。 403 Forbidden :直接拒絕HTTP請(qǐng)求,不處理。一般用來針對(duì)非法請(qǐng)求。 404 Not Found :你請(qǐng)求的資源未在服務(wù)端找到。比如你請(qǐng)求某個(gè)用戶的信息,服務(wù)端并沒有找到指定的用戶。 409 Conflict :表示請(qǐng)求的資源與服務(wù)端當(dāng)前的存狀態(tài)在沖突,請(qǐng)求無(wú)法被處理。
5xx Server Error(服務(wù)端錯(cuò)誤狀態(tài)碼)
500 Internal Server Error :服務(wù)端出問題了(通常是服務(wù)端出Bug了)。比如你服務(wù)端處理請(qǐng)求的時(shí)候突然拋出異常,但是異常并為在服務(wù)端被正確處理。 502 Bad Gateway :我們的網(wǎng)關(guān)將請(qǐng)求轉(zhuǎn)發(fā)到服務(wù)端,但是服務(wù)端返回的卻是一個(gè)錯(cuò)誤的響應(yīng)。
參考
https://www.restapitutorial.com/httpstatuscodes.html https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status https://en.wikipedia.org/wiki/List_of_HTTP_status_codes https://segmentfault.com/a/1190000018264501

