从 Java SE 6 开始,Sun Oracle JRE 中有一个内置的 HTTP 服务器。 Java 9 模块名称是jdk.httpserver https://docs.oracle.com/en/java/javase/17/docs/api/jdk.httpserver/module-summary.html. The com.sun.net.httpserver包摘要 https://docs.oracle.com/en/java/javase/17/docs/api/jdk.httpserver/com/sun/net/httpserver/package-summary.html概述了所涉及的类并包含示例。
Here's a kickoff example copypasted from their docs. You can just copy'n'paste'n'run it on Java 6+.
(to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source)
package com.stackoverflow.q3732109;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Test {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
应当指出的是,response.length()
他们的例子中的一部分很糟糕,本来应该是response.getBytes().length
。即便如此,getBytes()
方法必须显式指定您然后在响应标头中指定的字符集。唉,虽然误导了初学者,但这毕竟只是一个基本的启动示例。
执行它并访问 http://localhost:8000/test,您将看到以下响应:
这是回应
至于使用com.sun.*
类,请注意,与一些开发人员的想法相反,众所周知的常见问题解答绝对没有禁止这样做为什么开发人员不应该编写调用“sun”包的程序 https://www.oracle.com/java/technologies/faq-sun-packages.html。该常见问题解答涉及sun.*
包(例如sun.misc.BASE64Encoder
)供 Oracle JRE 内部使用(因此,当您在不同的 JRE 上运行应用程序时,这会杀死您的应用程序),而不是com.sun.*
包裹。 Sun/Oracle 也只是在 Java SE API 本身之上开发软件,就像 Apache 等其他公司一样。而且,这个具体HttpServer
必须存在于每个 JDK 中,因此绝对不会出现像 JDK 那样的“可移植性”问题sun.*
包裹。使用com.sun.*
课程只是灰心(但不是禁止的)当涉及到执行某些Java API,例如GlassFish(Java EE impl)、Mojarra(JSF impl)、Jersey(JAX-RS impl)等