Java SE includes HttpURLConnection for HTTP client functionality, but lacks an analogous server-side option. To avoid tedious manual parsing and formatting of HTTP requests and responses, consider the built-in HTTP server introduced in Java SE 6 located in the jdk.httpserver module.
Here's an example using the built-in HTTP server to handle requests:
package com.example; 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 SimpleHttpServer { 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.getBytes().length); // Specify charset for getBytes() OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } } }
Visit the specified URL (e.g., http://localhost:8000/test) with your browser to see the response:
This is the response
The com.sun. package is not forbidden for use as it pertains specifically to developer-written code that uses Sun/Oracle-specific APIs, not the built-in Java SE API. Thus, leveraging the com.sun. classes for the HTTP server is acceptable as these classes are included in all JDK implementations.
The above is the detailed content of How Can I Create a Simple HTTP Server Using the Java SE API?. For more information, please follow other related articles on the PHP Chinese website!