java httplistener
时间: 2023-08-30 08:10:35 浏览: 91
Java HttpListener is a class that enables developers to create a web server using the HTTP protocol. It is a part of the Java SE API and is available since version 6. The HttpListener class provides a simple and easy-to-use interface for developers to create HTTP servers, process incoming requests and send responses back to clients.
The HttpListener class provides methods for starting, stopping, and configuring the HTTP server. It also provides methods for registering request handlers that can process incoming requests and send responses back to clients. Additionally, the HttpListener class provides support for HTTPS and SSL/TLS encryption.
Here is an example of how to use the HttpListener class to create a simple HTTP server:
```
import com.sun.net.httpserver.*;
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
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();
}
}
}
```
In this example, we create an HttpServer instance listening on port 8080. We register a request handler for the root context ("/") that simply sends back a response. Finally, we start the server and it will listen for incoming requests.
阅读全文