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();
}
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。
入口文件:projects/servlet-http-status-codes-lab/ExploreHttpStatusCodes.java
本地运行步骤快速上手
- 点击上方“保存源码”保存为
ExploreHttpStatusCodes.java,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1374.zip
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a1361.zip