1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import lombok.SneakyThrows;
import java.io.File; import java.io.FileInputStream; import java.io.OutputStream;
public class MyHttpResponse {
private final OutputStream outputStream;
public MyHttpResponse(OutputStream outputStream) { this.outputStream = outputStream; }
@SneakyThrows public void sendRedirect(String uri) {
String path = System.getProperty("user.dir") + "/src" + "/main" + "/resources" + "/web"; File file = new File(path + uri);
if (!file.exists()) { String error = "404 File Not Found!"; this.outputStream.write(getResponseMessage("404", error).getBytes()); } else { FileInputStream fileInputStream = new FileInputStream(file); byte[] bytes = new byte[(int) file.length()]; fileInputStream.read(bytes); String result = new String(bytes); this.outputStream.write(getResponseMessage("200", result).getBytes()); } }
public String getResponseMessage(String code, String message) { return "HTTP/1.1 " + code + "\r\n" + "Content-type: " + "text/html" + "\r\n" + "Content-Length: " + message.length() + "\r\n" + "\r\n" + message; } }
|