Nuclear_Man_D icon

example HTTP server in Java

Nuclear_Man_D | PRO | 02/13/19 11:42:39 PM UTC | 0 ⭐ | 288 👁️ | Never ⏰ | []
Java |

1.02 KB

|

None

|

0 👍

/

0 👎

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;
 
// my simple implementation for an HTTP server in Java.
 
public class MyHTTPServer implements HttpHandler{
    private HttpServer server;
    public MyHTTPServer(int port) throws IOException {
        server = HttpServer.create(new InetSocketAddress(port), 0);
        server.createContext("/", this);
        server.setExecutor(null); // creates a default executor
    }
    public void handle(HttpExchange exchange) throws IOException {
        String path = exchange.getRequestURI().getPath();
        String response = /* put response here! */ "Hello World!  Path = "+path;
        os.write(response.getBytes());
        os.close();
    }
    public void start() {
        server.start();
    }
 
    public static void main(String[] args) throws IOException {
        // this program can execute!
        new MyHTTPServer(8080).start();
    }
}

Comments