/
on-line-javalex
/
HW_FORMS
Обзор
Документация
Войти
/
on-line-javalex
/
HW_FORMS
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Main.java
77 строк
3 KB
on-line-javalex
upload files
03 мар 2026, 07:47
Верифицирован
03 мар 2026, 07:47
468c7a8
Код
Авторство
О чём код?
package netology; import java.io.BufferedOutputStream; import java.io.IOException; import java.time.LocalDateTime; public class Main { public static void main(String[] args) { Server server = new Server(9999); server.addHandler("GET", "/messages", (request, out) -> { String last = request.getQueryParam("last"); String responseBody = "{\"last\":\"" + (last != null ? last : "null") + "\"}"; sendJsonResponse(out, responseBody); }); server.addHandler("POST", "/form", (request, out) -> { String name = request.getPostParam("name"); String age = request.getPostParam("age"); String responseBody = "{\"name\":\"" + name + "\", \"age\":\"" + age + "\"}"; sendJsonResponse(out, responseBody); }); server.addHandler("POST", "/upload", (request, out) -> { try { Part filePart = request.getPart("file"); if (filePart != null && filePart.isFile()) { String filename = filePart.getFilename(); byte[] content = filePart.getContent(); String responseBody = "{\"filename\":\"" + filename + "\", \"size\":" + content.length + "}"; sendJsonResponse(out, responseBody); } else { sendJsonResponse(out, "{\"error\":\"No file uploaded\"}"); } } catch (IOException e) { e.printStackTrace(); sendInternalError(out); } }); server.addHandler("GET", "/classic.html", (request, out) -> { try { byte[] content = ("<html><body><h1>Time: " + LocalDateTime.now() + "</h1></body></html>").getBytes(); String responseHeader = "HTTP/1.1 200 OK\r\n" + "Content-Type: text/html\r\n" + "Content-Length: " + content.length + "\r\n" + "Connection: close\r\n" + "\r\n"; out.write(responseHeader.getBytes()); out.write(content); } catch (IOException e) { e.printStackTrace(); } }); server.start(); } private static void sendJsonResponse(BufferedOutputStream out, String json) throws IOException { byte[] content = json.getBytes(); String header = "HTTP/1.1 200 OK\r\n" + "Content-Type: application/json\r\n" + "Content-Length: " + content.length + "\r\n" + "Connection: close\r\n" + "\r\n"; out.write(header.getBytes()); out.write(content); } private static void sendInternalError(BufferedOutputStream out) throws IOException { String response = "HTTP/1.1 500 Internal Server Error\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; out.write(response.getBytes()); } }