Created
March 26, 2021 18:19
-
-
Save lawrenceching/2b60de733602707820d91a3574f32495 to your computer and use it in GitHub Desktop.
The build-in, simplest 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
package me.imlc.demos; | |
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 JavaHttpServer { | |
public static void main(String[] args) throws IOException { | |
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); | |
server.createContext("/hello", new HttpHandler() { | |
@Override | |
public void handle(HttpExchange exchange) throws IOException { | |
String resp = "Hello, world!"; | |
exchange.sendResponseHeaders(200, resp.length()); | |
OutputStream os = exchange.getResponseBody(); | |
os.write(resp.getBytes()); | |
os.close(); | |
} | |
}); | |
server.setExecutor(null); | |
server.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment