Created
June 5, 2023 10:07
-
-
Save prashant-shahi/395e5a59efc85229d2647437e0b88d00 to your computer and use it in GitHub Desktop.
Simple HTTP Server in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 SimpleHttpServer { | |
public static void main(String[] args) throws IOException { | |
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); | |
server.createContext("/hello", new HelloHandler()); | |
server.setExecutor(null); | |
server.start(); | |
System.out.println("Server is listening on port 8080"); | |
} | |
static class HelloHandler implements HttpHandler { | |
@Override | |
public void handle(HttpExchange exchange) throws IOException { | |
String response = "Hello, World!"; | |
exchange.sendResponseHeaders(200, response.length()); | |
OutputStream outputStream = exchange.getResponseBody(); | |
outputStream.write(response.getBytes()); | |
outputStream.close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment