Skip to content

Instantly share code, notes, and snippets.

@gitawego
Last active December 17, 2019 02:56
Show Gist options
  • Save gitawego/14e15456e4d36a26aac7695648565329 to your computer and use it in GitHub Desktop.
Save gitawego/14e15456e4d36a26aac7695648565329 to your computer and use it in GitHub Desktop.
simple HTTP server in Java
package com.stackoverflow.q3732109;
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 Test {
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();
}
}
}
@gitawego
Copy link
Author

gitawego commented Jun 28, 2016

Since Java SE 6, there's a builtin HTTP server in Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.
ref: stackoverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment