在 Java 里写 HTTP 服务有多种方式,从原生到框架都有。下面按由简到繁给你介绍几种常见写法。
适合:简单接口、学习、工具类服务
Java 自带 com.sun.net.httpserver(JDK 自带,无需依赖)
import com.sun.net.httpserver.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new java.net.InetSocketAddress(8080), 0);
server.createContext("/hello", exchange -> {
String response = "{\"msg\":\"hello world\"}";
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, response.getBytes().length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(response.getBytes(StandardCharsets.UTF_8));
}
});
server.start();
System.out.println("Server started on 8080");
}
}
✅ 优点:无依赖
❌ 缺点:功能少、不适合大型项目
适合:真实项目、REST API、企业开发
使用 start.spring.io:
Spring Web@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Boot";
}
}
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
✅ 优点:生态最强、易扩展
❌ 缺点:稍重
适合:高并发、微服务、网关
ServerBootstrap bootstrap = new ServerBootstrap();
// 配置 EventLoopGroup
// 编写 ChannelHandler
// 绑定端口
⚠️ 代码较长,一般不直接写业务 HTTP 服务
| 场景 | 推荐 |
|---|---|
| 学习 / 小工具 | JDK HttpServer |
| 正常后端服务 | Spring Boot |
| 高性能服务 | Netty / Undertow |
| 微服务 | Spring Boot + Spring Cloud |
javac SimpleHttpServer.java
java SimpleHttpServer
curl http://localhost:8080/hello
如果你愿意,可以告诉我:
我可以直接给你可运行的完整代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。