JavaHttpServer是一個輕量級的Java HTTP服務器實現。它提供了高可靠性、高性能、高擴展性的Web應用柿子,完全可以替代一些商業Http服務器。
一、基本概念
JavaHttpServer是一個基於Java語言開發的輕量級Http服務器,是JavaSE(標準版)中自帶的網絡服務組件,無需安裝額外的插件或框架。它僅依賴於JRE,開發者可以直接調用Java標準API進行開發,是一種非常方便的開發工具。
JavaHttpServer在Java SE 6中引入,可以處理HTTP/1.1請求,支持靜態和動態生成內容,並支持SSL加密。它支持多種HTTP方法,如GET、POST、PUT、DELETE,支持Cookie、Session、緩存、壓縮、安全認證等功能。JavaHttpServer還提供了一組API,使得開發者可以方便地擴展JavaHttpServer,按照需求實現自己的Http服務。
二、使用方法
使用JavaHttpServer來開發一個Web應用程序是非常簡單的,以下是一個簡單的例子:
import com.sun.net.httpserver.*;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class MyHttpServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
String response = "Hello World!";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
在該例子中,代碼通過HttpServer對象創建了一個本地服務器並監聽8000端口。然後通過server.createContext()方法添加一個處理器MyHandler,根據用戶請求返回「Hello World!」。
三、主要功能
1. 路由和處理器
JavaHttpServer允許開發者通過註冊處理器來處理來自客戶端的請求,並將它們路由到正確的處理器。開發者可以使用HttpExchange對象來處理請求、響應數據和設置HTTP頭信息。以下代碼是一個使用基本路由和處理器的例子:
// 創建HttpServer,並命名它為server
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
// 創建上下文和處理器
server.createContext("/users", new UsersHandler());
server.createContext("/products", new ProductsHandler());
// 啟動服務器
server.start();
// 處理器UsersHandler
static class UsersHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
// 處理users路由
}
}
// 處理器ProductsHandler
static class ProductsHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
// 處理products路由
}
}
2. 靜態文件服務
JavaHttpServer也允許開發者通過添加靜態文件處理器來服務於靜態文件。以下是創建一個簡單的靜態文件處理器的例子:
// 創建靜態文件處理器對象
HttpHandler staticHandler = new StaticFileHandler();
// 創建HttpServer,並為根路由添加靜態文件處理器
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", staticHandler);
// 啟動服務器
server.start();
// 處理靜態文件的處理器
static class StaticFileHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath().substring(1);
if ("".equals(path)) {
path = "index.html";
}
InputStream stream = getClass().getResourceAsStream(path);
if (stream != null) {
byte[] bytes = IOUtils.toByteArray(stream);
exchange.sendResponseHeaders(200, bytes.length);
exchange.getResponseBody().write(bytes);
exchange.close();
} else {
exchange.sendResponseHeaders(404, 0);
exchange.close();
}
}
}
3. Cookie
JavaHttpServer能夠支持HTTP狀態管理,包括Cookies。開發者可以通過以下方法設置Cookie:
HttpExchange exchange = ...;
HttpHeaders headers = exchange.getResponseHeaders();
headers.add("Set-Cookie", "name=value; Domain=domain.com; Max-Age=1000; Path=/");
// 獲取Cookie
List cookies = headers.get("Cookie");
4. SSL
JavaHttpServer支持加密協議,並包含了SSL支持。以下是一個使用JavaHttpServer啟用SSL的例子:
// 實例化SSLContext
char[] password = "password".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("keystore.jks");
ks.load(fis, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, password);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// 啟用SSL
HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(8000), 0);
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
httpsServer.start();
5. 緩存和壓縮
JavaHttpServer能夠緩存靜態資源,同時提供壓縮機制。以下是一個使用JavaHttpServer緩存和壓縮的例子:
// 創建HttpServer,並啟動gzip壓縮和緩存
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
GzipFilter gzipFilter = new GzipFilter();
server.createContext("/static/", new StaticHandler());
server.createContext("/", new DynamicHandler());
server.setExecutor(null);
server.start();
// 靜態資源的處理器
static class StaticHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
File file = new File("static", exchange.getRequestURI().toString().substring(8));
if (file.exists()) {
byte[] bytes = Files.readAllBytes(file.toPath());
Headers headers = exchange.getResponseHeaders();
// 啟用gzip壓縮
headers.add("Content-Encoding", "gzip");
// 啟用緩存(緩存1分鐘)
headers.add("Cache-Control", "max-age=60");
// 壓縮文件並返回
OutputStream os = new GZIPOutputStream(exchange.getResponseBody());
os.write(bytes);
os.close();
exchange.close();
} else {
exchange.sendResponseHeaders(404, 0);
exchange.close();
}
}
}
// 動態資源的處理器
static class DynamicHandler implements HttpHandler {
public void handle(HttpExchange exchange) throws IOException {
Headers headers = exchange.getResponseHeaders();
// 啟用緩存(緩存1分鐘)
headers.add("Cache-Control", "max-age=60");
String response = "Hello World!";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
原創文章,作者:SYAVN,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/324607.html