如何用java搭建基于http的web服务器
时间: 2024-03-03 08:51:08 浏览: 117
搭建基于HTTP的Web服务器,可以通过Java中的HttpServer类实现。以下是简单的步骤:
1. 导入HttpServer类所在的包
```
import com.sun.net.httpserver.HttpServer;
```
2. 创建HttpServer对象
```
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
```
3. 创建处理请求的HttpHandler对象
```
HttpHandler handler = new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
String response = "Hello World!";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
};
```
4. 将HttpHandler对象与服务器绑定
```
server.createContext("/", handler);
```
5. 启动服务器
```
server.start();
```
完整的代码示例:
```
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 SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
HttpHandler handler = new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
String response = "Hello World!";
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
};
server.createContext("/", handler);
server.start();
}
}
```
以上是一个简单的HTTP服务器实现,你可以根据需要进行修改和扩展。
阅读全文