From ff7e5b88e75bda0d99614bead4f3b559023ca50a Mon Sep 17 00:00:00 2001 From: ulrich Date: Fri, 26 Mar 2021 16:11:42 +0000 Subject: [PATCH] FileHandler Behandlung gemeinsamer Response Headers --- src/de/uhilger/minsrv/handler/FileHandler.java | 28 ++++++++++++++++++++-------- 1 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/de/uhilger/minsrv/handler/FileHandler.java b/src/de/uhilger/minsrv/handler/FileHandler.java index 5884871..129cd57 100644 --- a/src/de/uhilger/minsrv/handler/FileHandler.java +++ b/src/de/uhilger/minsrv/handler/FileHandler.java @@ -26,18 +26,23 @@ import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; -import java.util.Set; import java.util.logging.Logger; /** * Die Klasse FileHandler dient zur Auslieferung von Dateiinhalten über * HTTP. - * + * + * Für das Streaming über HTTP wird die + * Auslieferung von Teilinhalten mit dem Accept-Ranges-Header angeboten und + * via Range-Header unterstützt. + * (vgl. https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests) + * * @author Ulrich Hilger * @version 0.1, 25. März 2021 */ @@ -113,7 +118,7 @@ if (file.exists()) { OutputStream os = e.getResponseBody(); Headers headers = e.getResponseHeaders(); - headers.add(ACCEPT_RANGES_HEADER, "bytes"); + setCommonHeaders(headers, file); e.sendResponseHeaders(SC_OK, file.length()); InputStream in = new FileInputStream(file); int b = in.read(); @@ -158,7 +163,7 @@ InputStream is = new FileInputStream(file); OutputStream os = e.getResponseBody(); Headers resHeaders = e.getResponseHeaders(); - resHeaders.add(ACCEPT_RANGES_HEADER, "bytes"); + setCommonHeaders(resHeaders, file); long responseLength = 0; long start = 0; long end; @@ -178,10 +183,6 @@ resHeaders.add(CONTENT_RANGE_HEADER, sb.toString()); responseLength += (end - start); } - resHeaders.add(CONTENT_TYPE, "video/mp4"); - SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); - Date date = new Date(file.lastModified()); - resHeaders.add(LAST_MODIFIED_DATE_HEADER, sdf.format(date)); e.sendResponseHeaders(SC_PARTIAL_CONTENT, responseLength); if (start > 0) { is.skip(start); @@ -200,6 +201,17 @@ sendNotFound(e, file.getName()); } } + + private void setCommonHeaders(Headers resHeaders, File file) throws IOException { + resHeaders.add(ACCEPT_RANGES_HEADER, "bytes"); + String mimeType = Files.probeContentType(file.toPath()); + if(mimeType != null) { + resHeaders.add(CONTENT_TYPE, mimeType); + } + SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz"); + Date date = new Date(file.lastModified()); + resHeaders.add(LAST_MODIFIED_DATE_HEADER, sdf.format(date)); + } /** * Die Byte-Ranges aus dem Range-Header ermitteln. -- Gitblit v1.9.3