簡易伺服器僅回應固定內容,完整 HTTP 伺服器需解析請求行、標頭、實體內容,並支援多種方法(GET、POST、HEAD)、狀態碼、MIME 類型對應。
public class HTTPrequest {
public String method, uri, version;
public Map headers = new HashMap<>();
public byte[] body;
public Socket clientSocket;
public InputStream inputStream;
public void parse(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// 解析請求行
String[] requestLine = reader.readLine().split("\\s+");
method = requestLine[0];
uri = requestLine[1];
version = requestLine[2];
// 解析標頭
String line;
while (!(line = reader.readLine()).isEmpty()) {
int idx = line.indexOf(':');
if (idx > 0) {
headers.put(line.substring(0, idx).trim(),
line.substring(idx + 1).trim());
}
}
// 讀取實體(簡化版)
if (headers.containsKey("Content-Length")) {
int len = Integer.parseInt(headers.get("Content-Length"));
body = new byte[len];
in.read(body);
}
}
}
Map 替代陣列儲存標頭,O(1) 查找此類別為靜態資源伺服器、Servlet 容器、REST API 框架的基石。