Created
December 29, 2018 18:46
-
-
Save idurucz/5a0d1ab7a27ef3c1c8bbf2316c4d209e to your computer and use it in GitHub Desktop.
Java HttpServer with HttpHandler to send response to client (uses com.sun.net.httpserver)
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 MyHttpServer { | |
public static void main(String[] args) throws Exception { | |
HttpServer server = HttpServer.create(new InetSocketAddress(80), 0); //listening port and max backlog | |
server.createContext("/", new MyHandler()); | |
server.setExecutor(null); | |
server.start(); | |
} | |
static class MyHandler implements HttpHandler { | |
@Override | |
public void handle(HttpExchange t) throws IOException { | |
String response = "hello world"; | |
t.sendResponseHeaders(200, response.length()); //response code and byte length | |
try (OutputStream os = t.getResponseBody()) { | |
os.write(response.getBytes()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment