java httplistener
时间: 2023-08-30 12:11:10 浏览: 41
The HttpListener class in Java is used to create a web server that listens for incoming HTTP requests and responds to them. It is part of the java.net package and provides a simple, lightweight way to implement HTTP servers in Java.
To use HttpListener, you need to create an instance of the class and configure it with a port number and any other options you need. Once the listener is configured, you can start it by calling the start() method.
Here's an example:
```
import java.net.*;
import java.io.*;
public class MyHttpServer {
public static void main(String[] args) throws IOException {
HttpListener listener = new HttpListener(8080); // create listener on port 8080
listener.start(); // start the listener
while (true) {
Socket clientSocket = listener.accept(); // accept incoming connection
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) { // read request
System.out.println(inputLine); // print request to console
}
// send response
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html; charset=UTF-8");
out.println("");
out.println("<html><body>Hello, world!</body></html>");
// clean up
out.close();
in.close();
clientSocket.close();
}
}
}
```
This example creates a listener on port 8080 and listens for incoming requests. When a request is received, it prints the request to the console and sends a simple "Hello, world!" response. Note that this is a very basic example and does not handle errors or security considerations.