温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用java写HTTP服务

发布时间:2026-10-22 04:20:26 来源:亿速云 阅读:106 作者:小樊 栏目:编程语言

在 Java 里写 HTTP 服务有多种方式,从原生到框架都有。下面按由简到繁给你介绍几种常见写法。


一、使用 JDK 原生(HttpServer,最简单)

适合:简单接口、学习、工具类服务

Java 自带 com.sun.net.httpserver(JDK 自带,无需依赖)

示例:一个返回 JSON 的 HTTP 服务

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");
    }
}

✅ 优点:无依赖
❌ 缺点:功能少、不适合大型项目


二、Spring Boot(最流行)

适合:真实项目、REST API、企业开发

1️⃣ 创建 Spring Boot 项目

使用 start.spring.io:

  • 选择 Spring Web

2️⃣ 写一个 Controller

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello() {
        return "Hello Spring Boot";
    }
}

3️⃣ 启动类

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

✅ 优点:生态最强、易扩展
❌ 缺点:稍重


三、使用 Undertow / Netty(高性能)

适合:高并发、微服务、网关

Netty 简单示例(核心思路)

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

如果你愿意,可以告诉我:

  • ✅ 是学习还是做项目
  • ✅ 是否需要 GET/POST
  • ✅ 是否要 返回 JSON / 接收参数

我可以直接给你可运行的完整代码。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手