Building a simple web server using SimpleHttpServer from the Java class library
Building a simple web server using SimpleHttpServer from the Java class library
In Java programming, we often need to build a simple web server to provide services. The SimpleHttpServer in the Java class library provides a simple way to achieve this goal.
SimpleHttpServer is a class library added in Java SE 6 that encapsulates all the functions of HTTP servers and provides a set of easy-to-use APIs for creating and managing web servers.
The following is an example code that demonstrates how to create a simple web server using SimpleHttpServer:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class SimpleWebServer {
public static void main(String[] args) throws IOException {
//Create an HttpServer instance and bind it to the specified IP address and port number
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8000), 0);
//Add a processor to handle all HTTP requests
server.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
//Set response header information
exchange.getResponseHeaders().set("Content-Type", "text/html; charset=UTF-8");
//Build response content
String response = "<h1>Hello, World!</h1>";
//Send response content
exchange.sendResponseHeaders(200, response.getBytes("UTF-8").length);
OutputStream outputStream = exchange.getResponseBody();
outputStream.write(response.getBytes("UTF-8"));
outputStream.close();
}
});
//Start Server
server.start();
System.out.println("Web Server is running on port 8000");
}
}
In the above example, we created a SimpleWebServer class where we created an HttpServer instance and bound it to the local host's 8000 port. Then, we added a processor to handle all HTTP requests. In the processor, we set the response header information and constructed a simple HTML page as the response content. Finally, we send the response content to the client by calling exchange. sendResponseHeaders () and the output stream.
To run this sample code, you need to add Java SE 6 or higher to your project and import the com. sun. net. httpserver package.
Using SimpleHttpServer can easily build a simple web server and handle HTTP requests. You can extend this sample code according to your own needs to achieve more complex functions, such as handling different URL paths, receiving and parsing request parameters, etc.