From 3c7e102765abd24168f3bc3205e1d8801412544a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Prante?= Date: Tue, 19 Dec 2023 17:51:53 +0100 Subject: [PATCH] add charset to text content type if missing --- gradle.properties | 2 +- .../http/server/BaseHttpResponseBuilder.java | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/gradle.properties b/gradle.properties index 9b0d2f4..ee6b1a3 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,3 +1,3 @@ group = org.xbib name = net-http -version = 4.0.7 +version = 4.0.8 diff --git a/net-http-server/src/main/java/org/xbib/net/http/server/BaseHttpResponseBuilder.java b/net-http-server/src/main/java/org/xbib/net/http/server/BaseHttpResponseBuilder.java index 486a2b6..d7f0c3c 100644 --- a/net-http-server/src/main/java/org/xbib/net/http/server/BaseHttpResponseBuilder.java +++ b/net-http-server/src/main/java/org/xbib/net/http/server/BaseHttpResponseBuilder.java @@ -156,6 +156,9 @@ public abstract class BaseHttpResponseBuilder implements HttpResponseBuilder { return this; } if (HttpHeaderNames.CONTENT_TYPE.equalsIgnoreCase(name.toString())) { + if (value.startsWith("text") && charset != null) { + value = value + "; charset=" + charset.name().toLowerCase(Locale.ROOT); + } setContentType(value); } if (headers.containsHeader(name)) { @@ -191,7 +194,7 @@ public abstract class BaseHttpResponseBuilder implements HttpResponseBuilder { if (done) { return this; } - this.contentType = contentType; + this.contentType = Objects.requireNonNull(contentType); return this; } @@ -351,13 +354,17 @@ public abstract class BaseHttpResponseBuilder implements HttpResponseBuilder { public void buildHeaders(long contentLength) { this.length = contentLength; if (!headers.containsHeader(HttpHeaderNames.CONTENT_TYPE)) { - if (contentType == null) { - contentType = HttpHeaderValues.APPLICATION_OCTET_STREAM; - } - if (!contentType.contains("charset=") && charset != null) { + if (contentType != null && contentType.startsWith("text") && !contentType.contains("charset") && charset != null) { contentType = contentType + "; charset=" + charset.name(); } headers.add(HttpHeaderNames.CONTENT_TYPE, contentType); + } else { + String s = headers.get(HttpHeaderNames.CONTENT_TYPE); + if (s != null && s.startsWith("text") && !s.contains("charset") && charset != null) { + s = s + "; charset=" + charset.name(); + } + headers.remove(HttpHeaderNames.CONTENT_TYPE); + headers.add(HttpHeaderNames.CONTENT_TYPE, s); } if (status == null) { logger.log(Level.WARNING, "no status code set by handlers, assuming OK");