http 服务在线程中创建
时间: 2023-09-10 19:13:30 浏览: 38
在 Java 中,可以使用 `java.net` 包中的 `HttpServer` 类来创建 HTTP 服务器。为了在新线程中创建 HTTP 服务器,可以使用 `java.util.concurrent` 包中的 `ExecutorService` 和 `Callable` 接口。
以下是一个示例代码,演示如何在新线程中创建 HTTP 服务器:
```java
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class HttpServerInThread {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Void> httpServerTask = new Callable<Void>() {
@Override
public Void call() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/hello", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = "Hello, world!";
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
server.setExecutor(null);
server.start();
return null;
}
};
executor.submit(httpServerTask);
}
}
```
在上面的代码中,我们首先创建了一个 `ExecutorService` 对象。然后,我们创建了一个 `Callable` 对象,其中定义了 HTTP 服务器的启动和停止逻辑。在 `call()` 方法中,我们创建了一个 `HttpServer` 对象,并调用了 `start()` 方法来启动 HTTP 服务器。最后,我们在 `main()` 方法中将 `httpServerTask` 提交给 `executor`,以便在新线程中运行 HTTP 服务器。
需要注意的是,上述代码使用了 `com.sun.net.httpserver.HttpServer` 类,这是 JDK 内置的 HTTP 服务器实现。在实际开发中,建议使用成熟的第三方 HTTP 服务器库,例如 Apache HttpComponents。