Skip to content

Commit ddb38ee

Browse files
committed
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
1 parent 2d86f22 commit ddb38ee

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,7 @@ private boolean isMultipart(MultiValueMap<String, ?> map, @Nullable MediaType co
384384
private void writeForm(MultiValueMap<String, Object> formData, @Nullable MediaType contentType,
385385
HttpOutputMessage outputMessage) throws IOException {
386386

387-
contentType = getMediaType(contentType);
387+
contentType = getFormContentType(contentType);
388388
outputMessage.getHeaders().setContentType(contentType);
389389

390390
Charset charset = contentType.getCharset();
@@ -402,15 +402,27 @@ private void writeForm(MultiValueMap<String, Object> formData, @Nullable MediaTy
402402
}
403403
}
404404

405-
private MediaType getMediaType(@Nullable MediaType mediaType) {
406-
if (mediaType == null) {
405+
/**
406+
* Return the content type used to write forms, given the preferred content type.
407+
* By default, this method returns the given content type, but adds the
408+
* {@linkplain #setCharset(Charset) charset} if it does not have one.
409+
* If {@code contentType} is {@code null},
410+
* {@code application/x-www-form-urlencoded; charset=UTF-8} is returned.
411+
*
412+
* <p>Subclasses can override this method to change this behavior.
413+
* @param contentType the preferred content type, can be {@code null}
414+
* @return the content type to be used
415+
* @since 5.2.2
416+
*/
417+
protected MediaType getFormContentType(@Nullable MediaType contentType) {
418+
if (contentType == null) {
407419
return DEFAULT_FORM_DATA_MEDIA_TYPE;
408420
}
409-
else if (mediaType.getCharset() == null) {
410-
return new MediaType(mediaType, this.charset);
421+
else if (contentType.getCharset() == null) {
422+
return new MediaType(contentType, this.charset);
411423
}
412424
else {
413-
return mediaType;
425+
return contentType;
414426
}
415427
}
416428

0 commit comments

Comments
 (0)