From ddb38eefeea1506bbf5bdefda4fd0c354381d79f Mon Sep 17 00:00:00 2001 From: Arjen Poutsma Date: Tue, 26 Nov 2019 10:50:08 +0100 Subject: [PATCH] Expose method to determine form content type This commit exposes the method that returns the media type used to write forms. By default, it includes the charset in the content type, which can cause issues with certain consumers. This commit changes the method from a private to a protected method, so that users can override the default behavior. Closes: gh-22971 --- .../converter/FormHttpMessageConverter.java | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java index ced2ae1767f9..76496f583291 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java @@ -384,7 +384,7 @@ private boolean isMultipart(MultiValueMap map, @Nullable MediaType co private void writeForm(MultiValueMap formData, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException { - contentType = getMediaType(contentType); + contentType = getFormContentType(contentType); outputMessage.getHeaders().setContentType(contentType); Charset charset = contentType.getCharset(); @@ -402,15 +402,27 @@ private void writeForm(MultiValueMap formData, @Nullable MediaTy } } - private MediaType getMediaType(@Nullable MediaType mediaType) { - if (mediaType == null) { + /** + * Return the content type used to write forms, given the preferred content type. + * By default, this method returns the given content type, but adds the + * {@linkplain #setCharset(Charset) charset} if it does not have one. + * If {@code contentType} is {@code null}, + * {@code application/x-www-form-urlencoded; charset=UTF-8} is returned. + * + *

Subclasses can override this method to change this behavior. + * @param contentType the preferred content type, can be {@code null} + * @return the content type to be used + * @since 5.2.2 + */ + protected MediaType getFormContentType(@Nullable MediaType contentType) { + if (contentType == null) { return DEFAULT_FORM_DATA_MEDIA_TYPE; } - else if (mediaType.getCharset() == null) { - return new MediaType(mediaType, this.charset); + else if (contentType.getCharset() == null) { + return new MediaType(contentType, this.charset); } else { - return mediaType; + return contentType; } }