java的com.sun.net.httpserver包下的类提供了一个高层级的http服务器API,可以用来构建内嵌的http服务器。支持http和https。这些API提供了一个RFC 2616 (HTTP 1.1)和RFC 2818 (HTTP over TLS)的部分实现。
https://docs.oracle.com/en/java/javase/19/docs/api/jdk.httpserver/com/sun/net/httpserver/package-summary.html
下面来实现一个简单的demo。
代码示例:
package com.thb;import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class Demo {public static void main(String[] args) throws IOException {// 用端口号8082、backlog数量等于5创建一个HttpServerfinal HttpServer server = HttpServer.create(new InetSocketAddress(8082), 5);// 创建线程池final ExecutorService threads = Executors.newFixedThreadPool(3);// 设置线程池server.setExecutor(threads);// 启动HttpServerserver.start();// 创建一个上下文HttpContext context = server.createContext("/hello");// 设置上下文的HttpHandlercontext.setHandler(new HttpHandler() {// 实现接口的函数public void handle(HttpExchange exchange) throws IOException {// 开始发送响应给客户端exchange.sendResponseHeaders(200, 0);// 取得输出流,用来写入输出内容OutputStream out = exchange.getResponseBody();out.write("welcome! You are success.".getBytes());out.flush();out.close();exchange.close();}});}}
首先查看端口号8082,没有被占用:
运行上面的程序,再查看端口号8082,已经被占用了,说明http服务器已经启动了:
在浏览器中输入网址http://localhost:8082/hello,看到了期望的内容,说明http服务器能够正常访问了