蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

在本地回环 HTTP 服务中实测 13 项客户端请求头、30 个 request 方法与请求头表格遍历

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreClientRequest.java
ExploreClientRequest.java342 行
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

public class ExploreClientRequest {

    static class SimpleRequestAdapter {
        private final HttpExchange ex;
        private final Map<String, Object> attrs = new LinkedHashMap<>();
        private final Map<String, List<String>> params = new LinkedHashMap<>();
        private final byte[] rawBody;
        private String sessionId;
        private Map<String, Object> session;

        SimpleRequestAdapter(HttpExchange ex) throws IOException {
            this.ex = ex;
            this.rawBody = readAllBytes(ex.getRequestBody());
            parseParams(ex.getRequestURI().getRawQuery());
            String cookieHdr = getHeader("Cookie");
            if (cookieHdr != null) {
                for (String part : cookieHdr.split(";")) {
                    String[] kv = part.trim().split("=", 2);
                    if (kv.length == 2 && "JSESSIONID".equals(kv[0])) {
                        this.sessionId = kv[1];
                    }
                }
            }
        }

        private void parseParams(String qs) throws IOException {
            if (qs == null || qs.isEmpty()) return;
            for (String p : qs.split("&")) {
                int i = p.indexOf('=');
                if (i > 0) {
                    String k = URLDecoder.decode(p.substring(0, i), "UTF-8");
                    String v = URLDecoder.decode(p.substring(i + 1), "UTF-8");
                    params.computeIfAbsent(k, x -> new ArrayList<>()).add(v);
                }
            }
        }

        String[] getCookies() {
            String h = getHeader("Cookie");
            return h == null ? new String[0] : h.split(";\\s*");
        }
        Enumeration<String> getAttributeNames() { return Collections.enumeration(attrs.keySet()); }
        Enumeration<String> getHeaderNames() { return Collections.enumeration(ex.getRequestHeaders().keySet()); }
        Enumeration<String> getParameterNames() { return Collections.enumeration(params.keySet()); }
        Map<String, Object> getSession() { return getSession(true); }
        Map<String, Object> getSession(boolean create) {
            if (session == null && create) session = new LinkedHashMap<>();
            return session;
        }
        Locale getLocale() { return Locale.CHINA; }
        Object getAttribute(String n) { return attrs.get(n); }
        void setAttribute(String n, Object v) { attrs.put(n, v); }
        byte[] getInputStreamBytes() { return rawBody; }
        String getAuthType() { return getHeader("Authorization") != null ? "BASIC" : null; }
        String getCharacterEncoding() { return "UTF-8"; }
        String getContentType() { return getHeader("Content-Type"); }
        String getContextPath() { return "/app"; }
        String getHeader(String n) { return ex.getRequestHeaders().getFirst(n); }
        String getMethod() { return ex.getRequestMethod(); }
        String getParameter(String n) { List<String> l = params.get(n); return (l == null || l.isEmpty()) ? null : l.get(0); }
        String getPathInfo() { return "/info"; }
        String getProtocol() { return ex.getProtocol(); }
        String getQueryString() { return ex.getRequestURI().getRawQuery(); }
        String getRemoteAddr() { return ex.getRemoteAddress().getAddress().getHostAddress(); }
        String getRemoteHost() { return ex.getRemoteAddress().getHostString(); }
        String getRemoteUser() { return "demoUser"; }
        String getRequestURI() { return ex.getRequestURI().getPath(); }
        String getRequestedSessionId() { return sessionId; }
        String getServletPath() { return "/main.jsp"; }
        String[] getParameterValues(String n) { List<String> l = params.get(n); return l == null ? null : l.toArray(new String[0]); }
        boolean isSecure() { return false; }
        int getContentLength() { return rawBody.length; }
        int getIntHeader(String n) { String v = getHeader(n); return v == null ? -1 : Integer.parseInt(v.trim()); }
        int getServerPort() { return ex.getLocalAddress().getPort(); }
    }

    private static byte[] readAllBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n;
        while ((n = in.read(buf)) != -1) out.write(buf, 0, n);
        return out.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        List<Map<String, Object>> cases = new ArrayList<>();
        final Map<String, String> capturedHeaders = new LinkedHashMap<>();
        final Map<String, Object> methodChecks = new LinkedHashMap<>();
        final List<String> tableRows = new ArrayList<>();

        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        try {
            server.createContext("/app/main.jsp/info", (HttpExchange ex) -> {
                SimpleRequestAdapter req = new SimpleRequestAdapter(ex);
                req.setAttribute("trace", "ok");
                Headers hdrs = ex.getRequestHeaders();
                for (String k : hdrs.keySet()) {
                    capturedHeaders.put(k.toLowerCase(Locale.ROOT), hdrs.getFirst(k));
                }
                // Exercise all 30 HttpServletRequest methods
                methodChecks.put("cookies_len", req.getCookies().length);
                methodChecks.put("has_attr_name", req.getAttributeNames().hasMoreElements());
                methodChecks.put("has_header_name", req.getHeaderNames().hasMoreElements());
                methodChecks.put("has_param_name", req.getParameterNames().hasMoreElements());
                methodChecks.put("session_false_null", req.getSession(false) == null);
                methodChecks.put("session_created", req.getSession() != null);
                methodChecks.put("locale", req.getLocale().toLanguageTag());
                methodChecks.put("attr_trace", req.getAttribute("trace"));
                methodChecks.put("input_body", new String(req.getInputStreamBytes(), StandardCharsets.UTF_8));
                methodChecks.put("auth_type", req.getAuthType());
                methodChecks.put("char_enc", req.getCharacterEncoding());
                methodChecks.put("content_type", req.getContentType());
                methodChecks.put("context_path", req.getContextPath());
                methodChecks.put("header_ua", req.getHeader("User-Agent"));
                methodChecks.put("method", req.getMethod());
                methodChecks.put("param_tag", req.getParameter("tag"));
                methodChecks.put("path_info", req.getPathInfo());
                methodChecks.put("protocol", req.getProtocol());
                methodChecks.put("query_string", req.getQueryString());
                methodChecks.put("remote_addr", req.getRemoteAddr());
                methodChecks.put("remote_host_nonempty", !req.getRemoteHost().isEmpty());
                methodChecks.put("remote_user", req.getRemoteUser());
                methodChecks.put("request_uri", req.getRequestURI());
                methodChecks.put("requested_sid", req.getRequestedSessionId());
                methodChecks.put("servlet_path", req.getServletPath());
                methodChecks.put("param_values_len", req.getParameterValues("tag").length);
                methodChecks.put("is_secure", req.isSecure());
                methodChecks.put("content_length", req.getContentLength());
                methodChecks.put("int_header_custom", req.getIntHeader("X-Retry"));
                methodChecks.put("server_port_positive", req.getServerPort() > 0);

                StringBuilder html = new StringBuilder("<table>");
                Enumeration<String> names = req.getHeaderNames();
                while (names.hasMoreElements()) {
                    String name = names.nextElement();
                    String val = req.getHeader(name);
                    tableRows.add(name.toLowerCase(Locale.ROOT));
                    html.append("<tr><td>").append(name).append("</td><td>").append(val).append("</td></tr>");
                }
                html.append("</table>");
                byte[] out = html.toString().getBytes(StandardCharsets.UTF_8);
                ex.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8");
                ex.sendResponseHeaders(200, out.length);
                try (OutputStream os = ex.getResponseBody()) { os.write(out); }
            });
            server.start();
            int port = server.getAddress().getPort();

            // Send raw HTTP/1.1 POST with all 13 standard browser request headers
            String body = "payload=hello";
            String rawReq =
                "POST /app/main.jsp/info?tag=a&tag=b HTTP/1.1\r\n"
                + "Host: 127.0.0.1:" + port + "\r\n"
                + "Accept: text/html,image/png\r\n"
                + "Accept-Charset: UTF-8\r\n"
                + "Accept-Encoding: gzip\r\n"
                + "Accept-Language: zh-CN,en-US\r\n"
                + "Authorization: Basic ZGVtbzp0ZXN0\r\n"
                + "Connection: close\r\n"
                + "Content-Type: application/x-www-form-urlencoded\r\n"
                + "Content-Length: " + body.getBytes(StandardCharsets.UTF_8).length + "\r\n"
                + "Cookie: JSESSIONID=SID123; theme=blue\r\n"
                + "If-Modified-Since: Wed, 21 Oct 2015 07:28:00 GMT\r\n"
                + "If-Unmodified-Since: Thu, 22 Oct 2015 07:28:00 GMT\r\n"
                + "Referer: http://127.0.0.1:" + port + "/index.jsp\r\n"
                + "User-Agent: LocalLabBrowser/1.0\r\n"
                + "X-Retry: 3\r\n"
                + "\r\n"
                + body;
            StringBuilder rawResp = new StringBuilder();
            try (Socket sock = new Socket("127.0.0.1", port)) {
                OutputStream os = sock.getOutputStream();
                os.write(rawReq.getBytes(StandardCharsets.UTF_8));
                os.flush();
                try (BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = br.readLine()) != null) rawResp.append(line).append("\n");
                }
            }

            // Case 1: browser_request_headers_catalog (all 13 headers)
            List<String> expected13 = Arrays.asList(
                "accept", "accept-charset", "accept-encoding", "accept-language",
                "authorization", "connection", "content-length", "cookie",
                "host", "if-modified-since", "if-unmodified-since", "referer", "user-agent"
            );
            int presentCount = 0;
            for (String h : expected13) {
                if (capturedHeaders.containsKey(h)) presentCount++;
            }
            Map<String, Object> exp1 = new LinkedHashMap<>();
            exp1.put("received_standard_headers", 13);
            exp1.put("user_agent", "LocalLabBrowser/1.0");
            exp1.put("accept_encoding", "gzip");

            Map<String, Object> act1 = new LinkedHashMap<>();
            act1.put("received_standard_headers", presentCount);
            act1.put("user_agent", capturedHeaders.get("user-agent"));
            act1.put("accept_encoding", capturedHeaders.get("accept-encoding"));
            addCase(cases, "browser_request_headers_catalog",
                "经由本地回环 TCP/HTTP 发送 13 项常见客户端请求头,验证服务端完整接收并解析每一项。",
                exp1, act1);

            // Case 2: http_servlet_request_30_methods
            Map<String, Object> exp2 = new LinkedHashMap<>();
            exp2.put("cookies_len", 2);
            exp2.put("has_attr_name", true);
            exp2.put("has_header_name", true);
            exp2.put("has_param_name", true);
            exp2.put("session_false_null", true);
            exp2.put("session_created", true);
            exp2.put("locale", "zh-CN");
            exp2.put("attr_trace", "ok");
            exp2.put("input_body", "payload=hello");
            exp2.put("auth_type", "BASIC");
            exp2.put("char_enc", "UTF-8");
            exp2.put("content_type", "application/x-www-form-urlencoded");
            exp2.put("context_path", "/app");
            exp2.put("header_ua", "LocalLabBrowser/1.0");
            exp2.put("method", "POST");
            exp2.put("param_tag", "a");
            exp2.put("path_info", "/info");
            exp2.put("protocol", "HTTP/1.1");
            exp2.put("query_string", "tag=a&tag=b");
            exp2.put("remote_addr", "127.0.0.1");
            exp2.put("remote_host_nonempty", true);
            exp2.put("remote_user", "demoUser");
            exp2.put("request_uri", "/app/main.jsp/info");
            exp2.put("requested_sid", "SID123");
            exp2.put("servlet_path", "/main.jsp");
            exp2.put("param_values_len", 2);
            exp2.put("is_secure", false);
            exp2.put("content_length", 13);
            exp2.put("int_header_custom", 3);
            exp2.put("server_port_positive", true);
            addCase(cases, "http_servlet_request_30_methods",
                "对真实回环 HTTP 请求逐一核验 HttpServletRequest 30 个常用方法语义与返回值。",
                exp2, methodChecks);

            // Case 3: enumerate_request_headers_table
            String respStr = rawResp.toString();
            Map<String, Object> exp3 = new LinkedHashMap<>();
            exp3.put("rendered_table", true);
            exp3.put("enumerated_header_count_ge_15", true);
            exp3.put("contains_ua_row", true);

            Map<String, Object> act3 = new LinkedHashMap<>();
            act3.put("rendered_table", respStr.contains("<table>") && respStr.contains("</table>"));
            act3.put("enumerated_header_count_ge_15", tableRows.size() >= 15);
            act3.put("contains_ua_row", respStr.contains("LocalLabBrowser/1.0"));
            addCase(cases, "enumerate_request_headers_table",
                "使用 Enumeration 遍历 request.getHeaderNames() 并将所有客户端请求头渲染为 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 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) {
            String s = (String) obj;
            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 '\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();
        }
        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(toJson(String.valueOf(e.getKey()))).append(":").append(toJson(e.getValue()));
            }
            return sb.append("}").toString();
        }
        return toJson(obj.toString());
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/jsp-client-request-lab/ExploreClientRequest.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreClientRequest.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:JSP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1390.zip

下载课程关联工程包:JSP

课程关联工程包(登记关联32章) · 含当前章节或实例 · mbskycom202612a1388.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习