The HttpServer
class in the Java API is a simple HTTP server that can be used to host static content, such as HTML, CSS, and JavaScript files, or to serve dynamic content generated by Java code.
Here is an example of how to use the HttpServer
class to host static content:
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 StaticContentServer { public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/", new StaticContentHandler()); server.start(); } } class StaticContentHandler implements HttpHandler { @Override 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(); } }
In this example, the StaticContentServer
class creates an HttpServer
object bound to the local host on port 8000, and registers a StaticContentHandler
as the handler for all requests. The StaticContentHandler
class implements the HttpHandler
interface and defines the handle
method, which is called for each incoming request.
The handle
method sends a simple "Hello World!" response to the client, with a status code of 200 (OK). The response is sent using the sendResponseHeaders
and getResponseBody
methods of the HttpExchange
object, which represents the current request and response.
You can run this example by compiling and running the StaticContentServer
class, and then accessing the server at http://localhost:8000/
using a web browser. You should see the "Hello World!" message displayed in the browser.
You can customize this example by modifying the response text and adding additional HTTP headers or by serving different content based on the request URI or other request parameters. You can also use the HttpServer
class to serve dynamic content generated by Java code by implementing custom HttpHandler
classes that generate the content on the fly.