HTTP 請求與回應的結構高度相似,皆由以下四個部分組成:
HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... <!doctype ...> <html> <head>...</head> <body> ... </body> </html>
狀態行包含 HTTP 版本、狀態碼,以及對應的簡短訊息。下表整理了伺服器常見的 HTTP 狀態碼與說明:
| 狀態碼 | 訊息 | 描述 |
|---|---|---|
| 100 | Continue | 僅部分請求被接收,若未被拒絕,客戶端應繼續請求 |
| 101 | Switching Protocols | 伺服器切換協定 |
| 200 | OK | 請求成功 |
| 201 | Created | 請求完成,新資源已建立 |
| 202 | Accepted | 請求已接受,但尚未處理完成 |
| 203 | Non-authoritative Information | 非授權資訊 |
| 204 | No Content | 無內容回應 |
| 205 | Reset Content | 重置內容 |
| 206 | Partial Content | 部分內容 |
| 300 | Multiple Choices | 提供超連結清單供用戶選擇,最多支援 5 個 |
| 301 | Moved Permanently | 請求頁面永久移動至新 URL |
| 302 | Found | 請求頁面暫時移動至新 URL |
| 303 | See Other | 請求頁面可在不同 URL 找到 |
| 304 | Not Modified | 內容未修改 |
| 305 | Use Proxy | 需使用 Proxy |
| 306 | Unused | 已棄用,但保留狀態碼 |
| 307 | Temporary Redirect | 暫時重導向 |
| 400 | Bad Request | 伺服器無法識別請求 |
| 401 | Unauthorized | 需要使用者名稱與密碼 |
| 402 | Payment Required | 保留狀態碼,目前未使用 |
| 403 | Forbidden | 禁止存取 |
| 404 | Not Found | 找不到請求頁面 |
| 405 | Method Not Allowed | 請求方法不被允許 |
| 406 | Not Acceptable | 伺服器只能產生客戶端無法接受的回應 |
| 407 | Proxy Authentication Required | 需先驗證 Proxy 伺服器 |
| 408 | Request Timeout | 請求逾時,連線中斷 |
| 409 | Conflict | 請求衝突 |
| 410 | Gone | 請求頁面不再可用 |
| 411 | Length Required | 缺少 Content-Length,伺服器拒絕請求 |
| 412 | Precondition Failed | 前置條件判斷為 false |
| 413 | Request Entity Too Large | 請求實體過大 |
| 414 | Request-URI Too Long | URL 過長,常見於 POST 轉 GET 附帶大量查詢參數 |
| 415 | Unsupported Media Type | 媒體類型不支援 |
| 417 | Expectation Failed | 期望失敗 |
| 500 | Internal Server Error | 伺服器內部錯誤 |
| 501 | Not Implemented | 伺服器不支援所需功能 |
| 502 | Bad Gateway | 上游伺服器回應無效 |
| 503 | Service Unavailable | 服務暫時不可用 |
| 504 | Gateway Timeout | 閘道逾時 |
| 505 | HTTP Version Not Supported | 不支援的 HTTP 版本 |
HttpServletResponse 類別提供以下方法設定狀態碼:
| # | 方法 | 說明 |
|---|---|---|
| 1 | public void setStatus(int statusCode) | 設定任意狀態碼。若回應包含特殊狀態碼與文件,務必在使用 PrintWriter 輸出內容前呼叫此方法 |
| 2 | public void sendRedirect(String url) | 產生 302 回應,並附帶 Location 標頭指向新文件 |
| 3 | public void sendError(int code, String message) | 將狀態碼(通常為 404)與簡短訊息自動嵌入 HTML 文件並回傳給客戶端 |
以下範例示範如何傳送 407 錯誤碼,瀏覽器將顯示「Need authentication!!!」:
<html>
<head>
<title>Setting HTTP Status Code</title>
</head>
<body>
<%
// 設定錯誤代碼與原因
response.sendError(407, "Need authentication!!!");
%>
</body>
</html>
您也可以嘗試其他狀態碼,觀察不同的回應行為。
原文連結:https://www.manongjc.com/jsp/jsp_http_status.html