Top Description Inners Fields Constructors Methods
org.springframework.http.converter

public Class FormHttpMessageConverter

extends Object
implements HttpMessageConverter<MultiValueMap<String, ?>>
Class Inheritance
All Implemented Interfaces
org.springframework.http.converter.HttpMessageConverter
Known Direct Subclasses
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter
Imports
java.io.FilterOutputStream, .IOException, .OutputStream, java.net.URLDecoder, .URLEncoder, java.nio.charset.Charset, .StandardCharsets, java.util.ArrayList, .Collections, .LinkedHashMap, .List, .Map, org.springframework.core.io.Resource, org.springframework.http.ContentDisposition, .HttpEntity, .HttpHeaders, .HttpInputMessage, .HttpOutputMessage, .MediaType, .StreamingHttpOutputMessage, org.springframework.lang.Nullable, org.springframework.util.Assert, .CollectionUtils, .LinkedMultiValueMap, .MimeTypeUtils, .MultiValueMap, .StreamUtils, .StringUtils

Implementation of HttpMessageConverter to read and write 'normal' HTML forms and also to write (but not read) multipart data (e.g. file uploads).

In other words, this converter can read and write the "application/x-www-form-urlencoded" media type as MultiValueMap<String, String>, and it can also write (but not read) the "multipart/form-data" and "multipart/mixed" media types as MultiValueMap<String, Object>.

Multipart Data

By default, "multipart/form-data" is used as the content type when writing multipart data. As of Spring Framework 5.2 it is also possible to write multipart data using other multipart subtypes such as "multipart/mixed" and "multipart/related", as long as the multipart subtype is registered as a supported media type and the desired multipart subtype is specified as the content type when writing the multipart data. Note that "multipart/mixed" is registered as a supported media type by default.

When writing multipart data, this converter uses other HttpMessageConverters to write the respective MIME parts. By default, basic converters are registered for byte array, String, and Resource. These can be overridden via setPartConverters or augmented via addPartConverter.

Examples

The following snippet shows how to submit an HTML form using the "multipart/form-data" content type.

RestTemplate restTemplate = new RestTemplate();
// AllEncompassingFormHttpMessageConverter is configured by default

MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("field 1", "value 1");
form.add("field 2", "value 2");
form.add("field 2", "value 3");
form.add("field 3", 4);  // non-String form values supported as of 5.1.4

restTemplate.postForLocation("https://example.com/myForm", form);

The following snippet shows how to do a file upload using the "multipart/form-data" content type.

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("field 1", "value 1");
parts.add("file", new ClassPathResource("myFile.jpg"));

restTemplate.postForLocation("https://example.com/myFileUpload", parts);

The following snippet shows how to do a file upload using the "multipart/mixed" content type.

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("field 1", "value 1");
parts.add("file", new ClassPathResource("myFile.jpg"));

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.MULTIPART_MIXED);

restTemplate.postForLocation("https://example.com/myFileUpload",
    new HttpEntity<>(parts, requestHeaders));

The following snippet shows how to do a file upload using the "multipart/related" content type.

MediaType multipartRelated = new MediaType("multipart", "related");

restTemplate.getMessageConverters().stream()
    .filter(FormHttpMessageConverter.class::isInstance)
    .map(FormHttpMessageConverter.class::cast)
    .findFirst()
    .orElseThrow(() -> new IllegalStateException("Failed to find FormHttpMessageConverter"))
    .addSupportedMediaTypes(multipartRelated);

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
parts.add("field 1", "value 1");
parts.add("file", new ClassPathResource("myFile.jpg"));

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(multipartRelated);

restTemplate.postForLocation("https://example.com/myFileUpload",
    new HttpEntity<>(parts, requestHeaders));

Miscellaneous

Some methods in this class were inspired by org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity.

Authors
Arjen Poutsma, Rossen Stoyanchev, Juergen Hoeller, Sam Brannen
Since
3.0
See Also
org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter, org.springframework.util.MultiValueMap

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
private static class
FormHttpMessageConverter.MultipartOutputStream

OutputStream that neither flushes nor closes.

Field Summary

Modifier and TypeField and Description
private Charset
public static final Charset
DEFAULT_CHARSET

The default charset used by the converter.

private static final MediaType
private Charset
private List<HttpMessageConverter<?>>
private List<MediaType>

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
addPartConverter(HttpMessageConverter<?> partConverter)

Add a message body converter.

public void
addSupportedMediaTypes(MediaType...
a var-args list of MediaType objects to add
supportedMediaTypes
)

Add MediaType objects to be supported by this converter.

private void
applyDefaultCharset()

Apply the configured charset as a default to registered part converters.

public boolean
canRead(Class<?>
the class to test for readability
clazz
,
MediaType
the media type to read (can be null if not specified); typically the value of a Content-Type header.
mediaType
)

Implements org.springframework.http.converter.HttpMessageConverter.canRead.

Indicates whether the given class can be read by this converter.

public boolean
canWrite(Class<?>
the class to test for writability
clazz
,
MediaType
the media type to write (can be null if not specified); typically the value of an Accept header.
mediaType
)

Implements org.springframework.http.converter.HttpMessageConverter.canWrite.

Indicates whether the given class can be written by this converter.

protected byte[]
generateMultipartBoundary()

Generate a multipart boundary.

protected String

Returns:

the filename, or null if not known
getFilename
(Object
the part to determine the file name for
part
)

Return the filename of the given multipart part.

protected MediaType

Returns:

the content type to be used
getFormContentType
(MediaType
the preferred content type (can be null)
contentType
)

Return the content type used to write forms, given the preferred content type.

protected HttpEntity<?>

Returns:

the part Object itself it is an HttpEntity, or a newly built HttpEntity wrapper for that part
getHttpEntity
(Object
the part to return an HttpEntity for
part
)

Return an HttpEntity for the given part Object.

public List<HttpMessageConverter<?>>
getPartConverters()

Return the configured converters for MIME parts.

public List<MediaType>
getSupportedMediaTypes()

Implements org.springframework.http.converter.HttpMessageConverter.getSupportedMediaTypes.

Return the list of media types supported by this converter.

private boolean
isFilenameCharsetSet()

When setMultipartCharset(Charset) is configured (i.e. RFC 2047, encoded-word syntax) we need to use ASCII for part headers, or otherwise we encode directly using the configured setCharset(Charset).

private boolean
isMultipart(MultiValueMap<String, ?> map, MediaType contentType)

public MultiValueMap<String, String>
read(Class<? extends MultiValueMap<String, ?>>
the type of object to return. This type must have previously been passed to the canRead method of this interface, which must have returned true.
clazz
,
HttpInputMessage
the HTTP input message to read from
inputMessage
)

Implements org.springframework.http.converter.HttpMessageConverter.read.

Read an object of the given type from the given input message, and returns it.

protected String
public void
setCharset(Charset charset)

Set the default character set to use for reading and writing form data when the request or response Content-Type header does not explicitly specify it.

public void
setMultipartCharset(Charset charset)

Set the character set to use when writing multipart data to encode file names.

public void
setPartConverters(List<HttpMessageConverter<?>> partConverters)

Set the message body converters to use.

public void
setSupportedMediaTypes(List<MediaType> supportedMediaTypes)

Set the list of MediaType objects supported by this converter.

public void
write(MultiValueMap<String, ?>
the object to write to the output message. The type of this object must have previously been passed to the canWrite method of this interface, which must have returned true.
map
,
MediaType
the content type to use when writing. May be null to indicate that the default content type of the converter must be used. If not null, this media type must have previously been passed to the canWrite method of this interface, which must have returned true.
contentType
,
HttpOutputMessage
the message to write to
outputMessage
)

Implements org.springframework.http.converter.HttpMessageConverter.write.

Write a given object to the given output message.

private void
writeBoundary(OutputStream os, byte[] boundary)

private static void
writeEnd(OutputStream os, byte[] boundary)

private void
writeForm(MultiValueMap<String, Object> formData, MediaType contentType, HttpOutputMessage outputMessage)

private void
private static void
private void
writePart(String name, HttpEntity<?> partEntity, OutputStream os)

private void
writeParts(OutputStream os, MultiValueMap<String, Object> parts, byte[] boundary)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

charsetback to summary
private Charset charset
DEFAULT_CHARSETback to summary
public static final Charset DEFAULT_CHARSET

The default charset used by the converter.

DEFAULT_FORM_DATA_MEDIA_TYPEback to summary
private static final MediaType DEFAULT_FORM_DATA_MEDIA_TYPE
multipartCharsetback to summary
private Charset multipartCharset
Annotations
@Nullable
partConvertersback to summary
private List<HttpMessageConverter<?>> partConverters
supportedMediaTypesback to summary
private List<MediaType> supportedMediaTypes

Constructor Detail

FormHttpMessageConverterback to summary
public FormHttpMessageConverter()

Method Detail

addPartConverterback to summary
public void addPartConverter(HttpMessageConverter<?> partConverter)

Add a message body converter. Such a converter is used to convert objects to MIME parts.

addSupportedMediaTypesback to summary
public void addSupportedMediaTypes(MediaType... supportedMediaTypes)

Add MediaType objects to be supported by this converter.

The supplied MediaType objects will be appended to the list of supported MediaType objects.

Parameters
supportedMediaTypes:MediaType[]

a var-args list of MediaType objects to add

Since
5.2
See Also
setSupportedMediaTypes(List)
applyDefaultCharsetback to summary
private void applyDefaultCharset()

Apply the configured charset as a default to registered part converters.

canReadback to summary
public boolean canRead(Class<?> clazz, MediaType mediaType)

Implements org.springframework.http.converter.HttpMessageConverter.canRead.

Doc from org.springframework.http.converter.HttpMessageConverter.canRead.

Indicates whether the given class can be read by this converter.

Parameters
clazz:Class<?>

the class to test for readability

mediaType:MediaType

the media type to read (can be null if not specified); typically the value of a Content-Type header.

Returns:boolean

true if readable; false otherwise

Annotations
@Override
canWriteback to summary
public boolean canWrite(Class<?> clazz, MediaType mediaType)

Implements org.springframework.http.converter.HttpMessageConverter.canWrite.

Doc from org.springframework.http.converter.HttpMessageConverter.canWrite.

Indicates whether the given class can be written by this converter.

Parameters
clazz:Class<?>

the class to test for writability

mediaType:MediaType

the media type to write (can be null if not specified); typically the value of an Accept header.

Returns:boolean

true if writable; false otherwise

Annotations
@Override
generateMultipartBoundaryback to summary
protected byte[] generateMultipartBoundary()

Generate a multipart boundary.

This implementation delegates to MimeTypeUtils#generateMultipartBoundary().

getFilenameback to summary
protected String getFilename(Object part)

Return the filename of the given multipart part. This value will be used for the Content-Disposition header.

The default implementation returns Resource#getFilename() if the part is a Resource, and null in other cases. Can be overridden in subclasses.

Parameters
part:Object

the part to determine the file name for

Returns:String

the filename, or null if not known

Annotations
@Nullable
getFormContentTypeback to summary
protected MediaType getFormContentType(MediaType contentType)

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 charset if it does not have one. If contentType is null, application/x-www-form-urlencoded; charset=UTF-8 is returned.

Subclasses can override this method to change this behavior.

Parameters
contentType:MediaType

the preferred content type (can be null)

Returns:MediaType

the content type to be used

Since
5.2.2
getHttpEntityback to summary
protected HttpEntity<?> getHttpEntity(Object part)

Return an HttpEntity for the given part Object.

Parameters
part:Object

the part to return an HttpEntity for

Returns:HttpEntity<?>

the part Object itself it is an HttpEntity, or a newly built HttpEntity wrapper for that part

getPartConvertersback to summary
public List<HttpMessageConverter<?>> getPartConverters()

Return the configured converters for MIME parts.

Since
5.3
getSupportedMediaTypesback to summary
public List<MediaType> getSupportedMediaTypes()

Implements org.springframework.http.converter.HttpMessageConverter.getSupportedMediaTypes.

Doc from org.springframework.http.converter.HttpMessageConverter.getSupportedMediaTypes.

Return the list of media types supported by this converter. The list may not apply to every possible target element type and calls to this method should typically be guarded via canWrite(clazz, null. The list may also exclude MIME types supported only for a specific class. Alternatively, use getSupportedMediaTypes(Class) for a more precise list.

Returns:List<MediaType>

the list of supported media types

Annotations
@Override
See Also
setSupportedMediaTypes(List), addSupportedMediaTypes(MediaType...)
isFilenameCharsetSetback to summary
private boolean isFilenameCharsetSet()

When setMultipartCharset(Charset) is configured (i.e. RFC 2047, encoded-word syntax) we need to use ASCII for part headers, or otherwise we encode directly using the configured setCharset(Charset).

isMultipartback to summary
private boolean isMultipart(MultiValueMap<String, ?> map, MediaType contentType)
readback to summary
public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException

Implements org.springframework.http.converter.HttpMessageConverter.read.

Doc from org.springframework.http.converter.HttpMessageConverter.read.

Read an object of the given type from the given input message, and returns it.

Parameters
clazz:Class<? extends MultiValueMap<String, ?>>

the type of object to return. This type must have previously been passed to the canRead method of this interface, which must have returned true.

inputMessage:HttpInputMessage

the HTTP input message to read from

Returns:MultiValueMap<String, String>

the converted object

Annotations
@Override
Exceptions
IOException:
in case of I/O errors
HttpMessageNotReadableException:
in case of conversion errors
serializeFormback to summary
protected String serializeForm(MultiValueMap<String, Object> formData, Charset charset)
setCharsetback to summary
public void setCharset(Charset charset)

Set the default character set to use for reading and writing form data when the request or response Content-Type header does not explicitly specify it.

As of 4.3, this is also used as the default charset for the conversion of text bodies in a multipart request.

As of 5.0, this is also used for part headers including Content-Disposition (and its filename parameter) unless (the mutually exclusive) multipartCharset is also set, in which case part headers are encoded as ASCII and filename is encoded with the encoded-word syntax from RFC 2047.

By default this is set to "UTF-8".

setMultipartCharsetback to summary
public void setMultipartCharset(Charset charset)

Set the character set to use when writing multipart data to encode file names. Encoding is based on the encoded-word syntax defined in RFC 2047 and relies on MimeUtility from jakarta.mail.

As of 5.0 by default part headers, including Content-Disposition (and its filename parameter) will be encoded based on the setting of setCharset(Charset) or UTF-8 by default.

Since
4.1.1
See Also
Encoded-Word
setPartConvertersback to summary
public void setPartConverters(List<HttpMessageConverter<?>> partConverters)

Set the message body converters to use. These converters are used to convert objects to MIME parts.

setSupportedMediaTypesback to summary
public void setSupportedMediaTypes(List<MediaType> supportedMediaTypes)

Set the list of MediaType objects supported by this converter.

See Also
addSupportedMediaTypes(MediaType...), getSupportedMediaTypes()
writeback to summary
public void write(MultiValueMap<String, ?> map, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException

Implements org.springframework.http.converter.HttpMessageConverter.write.

Doc from org.springframework.http.converter.HttpMessageConverter.write.

Write a given object to the given output message.

Parameters
map:MultiValueMap<String, ?>

the object to write to the output message. The type of this object must have previously been passed to the canWrite method of this interface, which must have returned true.

contentType:MediaType

the content type to use when writing. May be null to indicate that the default content type of the converter must be used. If not null, this media type must have previously been passed to the canWrite method of this interface, which must have returned true.

outputMessage:HttpOutputMessage

the message to write to

Annotations
@Override
@SuppressWarnings:unchecked
Exceptions
IOException:
in case of I/O errors
HttpMessageNotWritableException:
in case of conversion errors
writeBoundaryback to summary
private void writeBoundary(OutputStream os, byte[] boundary) throws IOException
writeEndback to summary
private static void writeEnd(OutputStream os, byte[] boundary) throws IOException
writeFormback to summary
private void writeForm(MultiValueMap<String, Object> formData, MediaType contentType, HttpOutputMessage outputMessage) throws IOException
writeMultipartback to summary
private void writeMultipart(MultiValueMap<String, Object> parts, MediaType contentType, HttpOutputMessage outputMessage) throws IOException
writeNewLineback to summary
private static void writeNewLine(OutputStream os) throws IOException
writePartback to summary
private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException
Annotations
@SuppressWarnings:unchecked
writePartsback to summary
private void writeParts(OutputStream os, MultiValueMap<String, Object> parts, byte[] boundary) throws IOException
org.springframework.http.converter back to summary

private Class FormHttpMessageConverter.MultipartHttpOutputMessage

extends Object
implements HttpOutputMessage
Class Inheritance
  • java.lang.Object
  • org.springframework.http.converter.FormHttpMessageConverter.MultipartHttpOutputMessage
All Implemented Interfaces
org.springframework.http.HttpOutputMessage, org.springframework.http.HttpMessage

Implementation of org.springframework.http.HttpOutputMessage used to write a MIME multipart.

Field Summary

Modifier and TypeField and Description
private final Charset
private final HttpHeaders
private boolean
private final OutputStream

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public OutputStream
getBody()

Implements org.springframework.http.HttpOutputMessage.getBody.

Return the body of the message as an output stream.

private byte[]
public HttpHeaders
getHeaders()

Implements org.springframework.http.HttpMessage.getHeaders.

Return the headers of this message.

private void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

charsetback to summary
private final Charset charset
headersback to summary
private final HttpHeaders headers
headersWrittenback to summary
private boolean headersWritten
outputStreamback to summary
private final OutputStream outputStream

Constructor Detail

MultipartHttpOutputMessageback to summary
public MultipartHttpOutputMessage(OutputStream outputStream, Charset charset)

Method Detail

getBodyback to summary
public OutputStream getBody() throws IOException

Implements org.springframework.http.HttpOutputMessage.getBody.

Doc from org.springframework.http.HttpOutputMessage.getBody.

Return the body of the message as an output stream.

Returns:OutputStream

the output stream body (never null)

Annotations
@Override
Exceptions
IOException:
in case of I/O errors
getBytesback to summary
private byte[] getBytes(String name)
getHeadersback to summary
public HttpHeaders getHeaders()

Implements org.springframework.http.HttpMessage.getHeaders.

Doc from org.springframework.http.HttpMessage.getHeaders.

Return the headers of this message.

Returns:HttpHeaders

a corresponding HttpHeaders object (never null)

Annotations
@Override
writeHeadersback to summary
private void writeHeaders() throws IOException
org.springframework.http.converter back to summary

private Class FormHttpMessageConverter.MultipartOutputStream

extends FilterOutputStream
Class Inheritance

OutputStream that neither flushes nor closes.

Field Summary

Inherited from java.io.FilterOutputStream:
out

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public void
close()

Overrides java.io.FilterOutputStream.close.

Implements java.io.Closeable.close.

Closes this output stream and releases any system resources associated with the stream.

public void
flush()

Overrides java.io.FilterOutputStream.flush.

Implements java.io.Flushable.flush.

Flushes this output stream and forces any buffered output bytes to be written out to the stream.

public void
write(byte[]
the data.
b
,
int
the start offset in the data.
off
,
int
the number of bytes to write.
let
)

Overrides java.io.FilterOutputStream.write.

Writes len bytes from the specified byte array starting at offset off to this output stream.

Inherited from java.io.FilterOutputStream:
writewrite

Constructor Detail

MultipartOutputStreamback to summary
public MultipartOutputStream(OutputStream out)

Method Detail

closeback to summary
public void close()

Overrides java.io.FilterOutputStream.close.

Implements java.io.Closeable.close.

Doc from java.io.FilterOutputStream.close.

Closes this output stream and releases any system resources associated with the stream.

Annotations
@Override
flushback to summary
public void flush()

Overrides java.io.FilterOutputStream.flush.

Implements java.io.Flushable.flush.

Doc from java.io.FilterOutputStream.flush.

Flushes this output stream and forces any buffered output bytes to be written out to the stream.

Annotations
@Override
writeback to summary
public void write(byte[] b, int off, int let) throws IOException

Overrides java.io.FilterOutputStream.write.

Doc from java.io.FilterOutputStream.write.

Writes len bytes from the specified byte array starting at offset off to this output stream.

Parameters
b:byte[]

the data.

off:int

the start offset in the data.

let:int

the number of bytes to write.

Annotations
@Override
Exceptions
IOException:
if an I/O error occurs.