Created
February 7, 2020 01:37
-
-
Save sergnechaev/dbc07974aa9407af0ed77f378c708545 to your computer and use it in GitHub Desktop.
Java HTTP server to log request details
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 java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.net.InetSocketAddress; | |
import java.util.stream.Collectors; | |
import com.sun.net.httpserver.HttpExchange; | |
import com.sun.net.httpserver.HttpHandler; | |
import com.sun.net.httpserver.HttpServer; | |
public class Server { | |
public static void main(String[] args) throws Exception { | |
HttpServer server = HttpServer.create(new InetSocketAddress(80), 0); | |
server.createContext("/", new MyHandler()); | |
server.setExecutor(null); // creates a default executor | |
server.start(); | |
} | |
static class MyHandler implements HttpHandler { | |
@Override | |
public void handle(HttpExchange t) throws IOException { | |
System.out.println("----------------------------------"); | |
System.out.println(t.getRequestURI()); | |
System.out.println(t.getRequestMethod()); | |
if (t.getRequestHeaders() != null && false == t.getRequestHeaders().isEmpty()) { | |
var headers = t.getRequestHeaders(); | |
for (var h : headers.keySet()) { | |
System.out.println(h + "= " + headers.get(h)); | |
} | |
} | |
System.out.println("----------------------------------"); | |
if (t.getRequestBody() != null) { | |
String result = new BufferedReader(new InputStreamReader(t.getRequestBody())).lines().collect(Collectors.joining("\n")); | |
System.out.println(result); | |
} | |
System.out.println("----------------------------------"); | |
System.out.println(); | |
System.out.println(); | |
String response = "ok"; | |
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