Skip to content

Instantly share code, notes, and snippets.

@yostane
Created January 3, 2021 12:06
Show Gist options
  • Select an option

  • Save yostane/9f69fc98764f3cd85275c9bc2c6e968a to your computer and use it in GitHub Desktop.

Select an option

Save yostane/9f69fc98764f3cd85275c9bc2c6e968a to your computer and use it in GitHub Desktop.
Java simple HTTP server
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 SimpleServer {
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();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment