serve html
This commit is contained in:
parent
c764c45807
commit
37ece02bd7
33
Main.java
33
Main.java
|
@ -4,6 +4,9 @@ import java.io.InputStreamReader;
|
|||
import java.io.OutputStream;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
@ -33,6 +36,7 @@ public class Main {
|
|||
}
|
||||
String request = requestBuilder.toString();
|
||||
// System.out.println(request);
|
||||
// PARSE THE REQUEST
|
||||
String[] requestLines = request.split("\r\n");
|
||||
String[] requestLine = requestLines[0].split(" ");
|
||||
String method = requestLine[0];
|
||||
|
@ -52,14 +56,41 @@ public class Main {
|
|||
method, path, version, host, headers.toString());
|
||||
System.out.println(accessLog);
|
||||
|
||||
Path filepath = getFilePath(path);
|
||||
if (Files.exists(filepath)) {
|
||||
// file exist
|
||||
String contentType = guessContentType(filepath);
|
||||
sendResponse(client, "200 OK", contentType, Files.readAllBytes(filepath));
|
||||
} else {
|
||||
// 404
|
||||
byte[] notFoundContent = "<h1>404 Something went wrong</h1>".getBytes();
|
||||
sendResponse(client, "404 Not Found", "text/html", notFoundContent);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static void sendResponse(Socket client, String status, String contentType, byte[] content)
|
||||
throws IOException {
|
||||
OutputStream clientOutput = client.getOutputStream();
|
||||
clientOutput.write("HTTP/1.1 200 OK\r\n".getBytes());
|
||||
clientOutput.write("ContentType: text/html\r\n".getBytes());
|
||||
clientOutput.write("\r\n".getBytes());
|
||||
clientOutput.write("<b>Hurray!!!1!</b>".getBytes());
|
||||
clientOutput.write(content);
|
||||
// These (windows) newlines indicate that the response is over
|
||||
clientOutput.write("\r\n\r\n".getBytes());
|
||||
clientOutput.flush();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private static String guessContentType(Path filepath) throws IOException {
|
||||
return Files.probeContentType(filepath);
|
||||
}
|
||||
|
||||
private static Path getFilePath(String path) {
|
||||
if ("/".equals(path)) {
|
||||
path = "/index.html";
|
||||
}
|
||||
return Paths.get("/home/andrzej/dev/java-http", path);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue