Servlet HTTP 状态码
梳理 HTTP 响应报文结构与 1xx 至 5xx 共 40 项标准 HTTP 状态码含义,对比 setStatus、sendRedirect 与 sendError 三个 Servlet 状态控制方法,并实测返回 HTTP 407 错误报告。
学完这一章,你能够
- 梳理 HTTP 响应报文结构与 1xx 至 5xx 共 40 项标准 HTTP 状态码含义,对比 setStatus、sendRedirect 与 sendError 三个 Servlet 状态控制方法,并实测返回 HTTP 407 错误报告。
HTTP 报文结构与标准状态码一览
HTTP 请求与 HTTP 响应在报文格式上高度对称,均由四段构成:1)初始行(响应中为状态行)后接回车换行符(CRLF);2)零个或多个报头行,每行以 CRLF 结束;3)单独一个空白行(CRLF)用于标示头部结束;4)可选的消息主体(如 HTML 页面、文件或表单载荷)。例如典型成功响应的首行 `HTTP/1.1 200 OK` 即依次给出了 HTTP 协议版本(`HTTP/1.1`)、三位数字状态码(`200`)和简短原因短语(`OK`)。下表汇总了 Web 服务器可能返回的 1xx(信息)、2xx(成功)、3xx(重定向)、4xx(客户端错误)与 5xx(服务端错误)共 40 个标准状态码(并补全了传统简表中留空的 203–206、304、305、417 说明)。
在 Servlet 中设置 HTTP 状态码的三种方法
`HttpServletResponse` 提供三个主要方法控制状态码:`setStatus(int)` 用于自定义状态码并保留自行输出响应体的控制权(务必在通过 `PrintWriter` 提交响应体前调用);`sendRedirect(String)` 便捷生成 `302` 状态码与 `Location` 响应头;`sendError(int, String)` 则发送 4xx/5xx 错误状态码并清空未提交缓冲区,交由容器渲染默认错误报告或匹配的 `<error-page>`。
HTTP 407 错误状态码实例与容器错误报告
在 `showError` 示例中,`doGet()` 直接调用 `response.sendError(407, "Need authentication!!!")` 向客户端发送 407(Proxy Authentication Required)代理身份验证错误响应(`doPost()` 委托 `doGet()`)。访问该 Servlet 时,容器(例如历史示例中的 Apache Tomcat 5.5.29)会自动生成标准化的状态报告页面:标题显示 `HTTP Status 407 - Need authentication!!!`,正文分项列明 `type Status report`、`message Need authentication!!!`、`description The client must first authenticate itself with the proxy (Need authentication!!!).` 及底部容器版本标识(生产环境通常建议关闭或自定义默认错误页以防泄露容器版本号)。本站已在本地回环 HTTP 服务上实测 200/201/204/302(+Location)/400/404/407/500 状态码及 407 HTML 错误报告输出。
常见 HTTP 状态码速查表(1xx–5xx)
| 状态码 | 原因短语 | 技术含义说明 |
|---|---|---|
| 100 | Continue | 服务器已收到请求初始部分且未拒绝,客户端可继续发送剩余请求体。 |
| 101 | Switching Protocols | 服务器同意按客户端 Upgrade 头要求切换传输协议(如升级到 WebSocket)。 |
| 200 | OK | 请求已成功处理,响应体包含对应结果。 |
| 201 | Created | 请求成功并在服务端创建了新资源。 |
| 202 | Accepted | 服务器已受理请求但尚未处理完毕,常用于异步任务。 |
| 203 | Non-Authoritative Information | 请求成功,但返回的元数据经过中间代理转换而非直接来自源服务器。 |
| 204 | No Content | 服务器成功处理了请求,但响应不包含任何消息主体。 |
| 205 | Reset Content | 请求成功,指示客户端重置触发本次请求的文档视图(如清空表单)。 |
| 206 | Partial Content | 服务器成功处理了带 Range 头的范围请求,仅返回资源的部分字节。 |
| 300 | Multiple Choices | 目标资源存在多个可选表示或地址,客户端或用户可从中择一跳转。 |
| 301 | Moved Permanently | 所请求资源已永久迁移至 Location 头指定的新 URL。 |
| 302 | Found | 所请求资源临时位于 Location 头指定的新 URL,后续请求仍应使用原地址。 |
| 303 | See Other | 指示客户端应改用 GET 方法向 Location 指定的新 URL 获取结果。 |
| 304 | Not Modified | 经条件请求校验,客户端缓存的资源自上次获取后未发生变化,可直接复用本地缓存。 |
| 305 | Use Proxy | 历史状态码,曾表示必须通过 Location 指定的代理访问目标资源(现代规范已废弃)。 |
| 306 | Unused | 早期 HTTP 草案保留的状态码,现已停用但编号保留。 |
| 307 | Temporary Redirect | 临时重定向至新 URL,并严格要求客户端在跳转时保持原 HTTP 请求方法与请求体不变。 |
| 400 | Bad Request | 客户端请求存在语法错误或无效参数,服务器无法理解或处理。 |
| 401 | Unauthorized | 访问目标资源需要提供有效的用户身份认证凭据。 |
| 402 | Payment Required | 保留状态码,预留给数字支付或付费访问场景。 |
| 403 | Forbidden | 服务器已理解请求但拒绝授权访问目标资源。 |
| 404 | Not Found | 服务器未能找到与请求 URI 匹配的资源。 |
| 405 | Method Not Allowed | 目标资源不支持当前请求使用的 HTTP 动词(响应常附带 Allow 头)。 |
| 406 | Not Acceptable | 服务器无法生成满足客户端 Accept 系列协商头要求的响应表示。 |
| 407 | Proxy Authentication Required | 请求放行前客户端必须先向中间代理服务器完成身份验证。 |
| 408 | Request Timeout | 服务器等待客户端发送完整请求的时间已超过超时阈值。 |
| 409 | Conflict | 请求与目标资源当前状态存在冲突(如版本并发修改冲突)而无法完成。 |
| 410 | Gone | 目标资源已被永久移除且不再提供转发地址。 |
| 411 | Length Required | 服务器要求请求必须包含有效的 Content-Length 头,否则拒绝处理。 |
| 412 | Precondition Failed | 请求头中给出的先决条件(如 If-Unmodified-Since)在服务端求值为假。 |
| 413 | Request Entity Too Large | 请求消息体大小超出服务器允许处理的上限。 |
| 414 | Request-URI Too Long | 请求目标 URI 长度超出服务器可解析的限制(例如将大体积 POST 改为 GET 传参)。 |
| 415 | Unsupported Media Type | 服务器不支持请求体采用的 Content-Type 媒体格式。 |
| 417 | Expectation Failed | 服务器无法满足请求头 Expect(如 100-continue)提出的要求。 |
| 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)`:设置任意 HTTP 状态码;若同时输出自定义响应文档,必须在通过 PrintWriter 写出内容并提交响应之前调用。 |
| 2 | `public void sendRedirect(String url)`:发送 302 临时重定向响应并附带指向新位置的 Location 响应头。 |
| 3 | `public void sendError(int code, String message)`:发送指定错误状态码(如 404、407)及自定义原因消息,交由容器或自定义 error-page 生成 HTML 错误报告。 |
HTTP 407 容器默认错误报告示例框
| 示例名称 | 渲染内容摘要 |
|---|---|
| HTTP Status 407 状态报告页 | 调用 response.sendError(407, "Need authentication!!!") 后容器生成的标准错误报告,依次包含标题 HTTP Status 407 - Need authentication!!!、报告类型 Status report、消息文本、代理认证描述及容器版本页脚。 |
实测 HTTP 200 响应格式、多状态码矩阵、302 重定向及 407 sendError 错误报告
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class ExploreHttpStatusCodes {
public static void main(String[] args) throws Exception {
List<Map<String, Object>> cases = new ArrayList<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
try {
server.createContext("/status", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String q = exchange.getRequestURI().getRawQuery();
int code = Integer.parseInt(q.replace("code=", ""));
if (code == 204 || code == 304) {
exchange.sendResponseHeaders(code, -1);
exchange.close();
return;
}
byte[] body = ("status=" + code).getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=UTF-8");
exchange.sendResponseHeaders(code, body.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(body);
}
}
});
server.createContext("/redirect", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
exchange.getResponseHeaders().set("Location", "/status?code=200");
exchange.sendResponseHeaders(302, -1);
exchange.close();
}
});
server.createContext("/showError", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String msg = "Need authentication!!!";
String html = "<!DOCTYPE html><html><head><title>HTTP Status 407 - " + msg + "</title></head><body>"
+ "<h1>HTTP Status 407 - " + msg + "</h1>"
+ "<p><b>type</b> Status report</p>"
+ "<p><b>message</b> " + msg + "</p>"
+ "<p><b>description</b> The client must first authenticate itself with the proxy (" + msg + ").</p>"
+ "</body></html>";
byte[] body = html.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8");
exchange.sendResponseHeaders(407, body.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(body);
}
}
});
server.start();
int port = server.getAddress().getPort();
// Case 1: HTTP/1.1 200 OK status line & message structure
HttpURLConnection c200 = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/status?code=200").openConnection();
int code200 = c200.getResponseCode();
String statusLine200 = c200.getHeaderField(0);
String body200 = readAll(c200.getInputStream());
c200.disconnect();
Map<String, Object> exp1 = new LinkedHashMap<>();
exp1.put("status_line", "HTTP/1.1 200 OK");
exp1.put("code", 200);
exp1.put("body", "status=200");
Map<String, Object> act1 = new LinkedHashMap<>();
act1.put("status_line", statusLine200);
act1.put("code", code200);
act1.put("body", body200);
addCase(cases, "http_message_structure_200",
"实测 HTTP 响应初始状态行 HTTP/1.1 200 OK、响应头与响应正文结构。",
exp1, act1);
// Case 2: setStatus across 2xx/4xx/5xx & sendRedirect 302 with Location
int code201 = fetchStatus(port, "/status?code=201");
int code204 = fetchStatus(port, "/status?code=204");
int code400 = fetchStatus(port, "/status?code=400");
int code404 = fetchStatus(port, "/status?code=404");
int code500 = fetchStatus(port, "/status?code=500");
HttpURLConnection cRedir = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/redirect").openConnection();
cRedir.setInstanceFollowRedirects(false);
int code302 = cRedir.getResponseCode();
String location = cRedir.getHeaderField("Location");
cRedir.disconnect();
Map<String, Object> exp2 = new LinkedHashMap<>();
exp2.put("created_201", 201);
exp2.put("no_content_204", 204);
exp2.put("redirect_302", 302);
exp2.put("redirect_location", "/status?code=200");
exp2.put("bad_request_400", 400);
exp2.put("not_found_404", 404);
exp2.put("server_error_500", 500);
Map<String, Object> act2 = new LinkedHashMap<>();
act2.put("created_201", code201);
act2.put("no_content_204", code204);
act2.put("redirect_302", code302);
act2.put("redirect_location", location);
act2.put("bad_request_400", code400);
act2.put("not_found_404", code404);
act2.put("server_error_500", code500);
addCase(cases, "http_status_matrix_and_redirect",
"实测 201/204/302(+Location)/400/404/500 多类状态码响应与不自动跟随重定向时的 Location 头读取。",
exp2, act2);
// Case 3: sendError(407, "Need authentication!!!") status report
HttpURLConnection c407 = (HttpURLConnection) new URL("http://127.0.0.1:" + port + "/showError").openConnection();
int code407 = c407.getResponseCode();
String errBody = readAll(c407.getErrorStream());
c407.disconnect();
Map<String, Object> exp3 = new LinkedHashMap<>();
exp3.put("status_code", 407);
exp3.put("contains_heading", true);
exp3.put("contains_message", true);
Map<String, Object> act3 = new LinkedHashMap<>();
act3.put("status_code", code407);
act3.put("contains_heading", errBody.contains("HTTP Status 407 - Need authentication!!!"));
act3.put("contains_message", errBody.contains("The client must first authenticate itself with the proxy"));
addCase(cases, "http_407_send_error_response",
"实测 /showError 返回 HTTP 407 Proxy Authentication Required 状态码与包含 Need authentication!!! 的 HTML 错误报告。",
exp3, act3);
} finally {
server.stop(0);
}
Map<String, Object> root = new LinkedHashMap<>();
root.put("version", "OpenJDK " + System.getProperty("java.version"));
root.put("cases", cases);
System.out.println(toJson(root));
}
private static int fetchStatus(int port, String path) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + port + path).openConnection();
int code = conn.getResponseCode();
InputStream stream = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
if (stream != null) readAll(stream);
conn.disconnect();
return code;
}
private static String readAll(InputStream in) throws IOException {
if (in == null) return "";
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
private static void addCase(List<Map<String, Object>> cases, String name, String summary, Object expected, Object actual) {
Map<String, Object> c = new LinkedHashMap<>();
c.put("name", name);
c.put("summary", summary);
c.put("expected", expected);
c.put("actual", actual);
c.put("passed", Objects.equals(expected, actual));
cases.add(c);
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof Boolean || obj instanceof Number) return obj.toString();
if (obj instanceof String) return escapeString((String) obj);
if (obj instanceof List<?>) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) obj;
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(",");
sb.append(toJson(list.get(i)));
}
return sb.append("]").toString();
}
if (obj instanceof Map<?, ?>) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : ((Map<?, ?>) obj).entrySet()) {
if (!first) sb.append(",");
first = false;
sb.append(escapeString(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
}
return sb.append("}").toString();
}
return escapeString(String.valueOf(obj));
}
private static String escapeString(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"': sb.append("\\\""); break;
case '\\': sb.append("\\\\"); break;
case '\b': sb.append("\\b"); break;
case '\f': sb.append("\\f"); break;
case '\n': sb.append("\\n"); break;
case '\r': sb.append("\\r"); break;
case '\t': sb.append("\\t"); break;
default:
if (ch < 0x20) sb.append(String.format("\\u%04x", (int) ch));
else sb.append(ch);
}
}
return sb.append("\"").toString();
}
}
- 确认回环服务端准确输出 HTTP/1.1 200 OK、201/204/302(+Location)/400/404/500 状态码,以及 /showError 返回 407 与含 Need authentication!!! 的 HTML 错误报告。
所需环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
当前源码 SHA256:fba18a98fe0964915e0afd96120d0011266ef05af9ce96529fea90e4ce0102b3
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
ZIP SHA256:4ea3fea05ae91d0c43029926ebe95a5f70ce17cb84cb472bdb1d7f0d5e6ce0b2
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
`response.setStatus(404)` 与 `response.sendError(404, "Not Found")` 在 Servlet 容器中的行为有何不同?
展开参考解答
`setStatus(404)` 仅修改响应状态码,容器仍会照常输出你在 Servlet 中自行写入的响应体;而 `sendError(404, msg)` 会清空未提交缓冲区并将控制权交给容器,由容器渲染默认错误页面或转发到 `web.xml` 中匹配的 `<error-page>`。