Home >Java >javaTutorial >How to Create a Simple HTTP Server in Java using the Java SE API?
Creating a Simple HTTP Server in Java with the Java SE API
The Java SE API provides the HttpURLConnection class for HTTP client Funktionalität. However, this leaves you with the task of manually parsing HTTP requests and formatting HTTP responses, which can be tedious and error-prone.
Fortunately, as of Java SE 6, there is a built-in HTTP server available in the jdk.httpserver module (com.sun.net.httpserver in earlier versions).
Here's a simple example adapted from the documentation:
import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class MyHttpServer { public static void main(String[] args) throws Exception { HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); server.createContext("/test", new MyHandler()); server.setExecutor(null); // creates a default executor server.start(); } static class MyHandler implements HttpHandler { @Override 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(); } } }
This server responds with "This is the response" when a GET request is sent to http://localhost:8000/test.
Note:
While using com.sun.* classes is discouraged for implementation purposes, it is not forbidden for utility classes like this HTTP server.
The above is the detailed content of How to Create a Simple HTTP Server in Java using the Java SE API?. For more information, please follow other related articles on the PHP Chinese website!