Java Code Examples for org.springframework.http.MediaType#MULTIPART_FORM_DATA

The following examples show how to use org.springframework.http.MediaType#MULTIPART_FORM_DATA . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FormHttpMessageConverter.java    From onetwo with Apache License 2.0 6 votes vote down vote up
private void writeMultipart(final MultiValueMap<String, Object> parts,
		HttpOutputMessage outputMessage) throws IOException {

	final byte[] boundary = generateMultipartBoundary();
	Map<String, String> parameters = new HashMap<>(2);
	parameters.put("boundary", new String(boundary, "US-ASCII"));
	if (!isFilenameCharsetSet()) {
		parameters.put("charset", this.charset.name());
	}

	MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
	HttpHeaders headers = outputMessage.getHeaders();
	headers.setContentType(contentType);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> {
			writeParts(outputStream, parts, boundary);
			writeEnd(outputStream, boundary);
		});
	}
	else {
		writeParts(outputMessage.getBody(), parts, boundary);
		writeEnd(outputMessage.getBody(), boundary);
	}
}
 
Example 2
Source File: FormHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage)
		throws IOException {

	final byte[] boundary = generateMultipartBoundary();
	Map<String, String> parameters = new LinkedHashMap<>(2);
	if (!isFilenameCharsetSet()) {
		parameters.put("charset", this.charset.name());
	}
	parameters.put("boundary", new String(boundary, StandardCharsets.US_ASCII));

	MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
	HttpHeaders headers = outputMessage.getHeaders();
	headers.setContentType(contentType);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> {
			writeParts(outputStream, parts, boundary);
			writeEnd(outputStream, boundary);
		});
	}
	else {
		writeParts(outputMessage.getBody(), parts, boundary);
		writeEnd(outputMessage.getBody(), boundary);
	}
}
 
Example 3
Source File: FormHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException {
	final byte[] boundary = generateMultipartBoundary();
	Map<String, String> parameters = Collections.singletonMap("boundary", new String(boundary, "US-ASCII"));

	MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
	HttpHeaders headers = outputMessage.getHeaders();
	headers.setContentType(contentType);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
			@Override
			public void writeTo(OutputStream outputStream) throws IOException {
				writeParts(outputStream, parts, boundary);
				writeEnd(outputStream, boundary);
			}
		});
	}
	else {
		writeParts(outputMessage.getBody(), parts, boundary);
		writeEnd(outputMessage.getBody(), boundary);
	}
}
 
Example 4
Source File: WxApiHttpRequest.java    From FastBootWeixin with Apache License 2.0 6 votes vote down vote up
/**
 * 针对下面这个比较恶心的魔法逻辑的说明:
 * 由于Spring5在对ContentType是MULTIPART_FORM_DATA的头处理时自动添加了charset参数。
 * see org.springframework.http.converter.FormHttpMessageConverter.writeMultipart
 * 如果设置了multipartCharset,则不会添加charset参数。
 * 但是在获取filename时又去判断如果设置了multipartCharset,则调用MimeDelegate.encode(filename, this.multipartCharset.name())
 * 对filename进行encode,但是MimeDelegate调用了javax.mail.internet.MimeUtility这个类,这个类有可能没有被依赖进来,不是强依赖的
 * 故会导致一样的报错。实在没办法切入源码了,故加入下面这个逻辑。
 * 在Spring4中在multipartCharset为空时,也不会自动添加charset,故没有此问题。
 * 而根本原因是微信的服务器兼容性太差了,header中的charset是有http标准规定的,竟然不兼容!
 *
 * @return OutputStream
 * @throws IOException
 */
@Override
public OutputStream getBody() throws IOException {
    HttpHeaders httpHeaders = this.delegate.getHeaders();
    MediaType contentType = httpHeaders.getContentType();
    if (contentType != null && contentType.includes(MediaType.MULTIPART_FORM_DATA)) {
        Map<String, String> parameters = contentType.getParameters();
        if (parameters.containsKey("charset")) {
            Map<String, String> newParameters = new LinkedHashMap<>(contentType.getParameters());
            newParameters.remove("charset");
            MediaType newContentType = new MediaType(MediaType.MULTIPART_FORM_DATA, newParameters);
            httpHeaders.setContentType(newContentType);
        }
    }
    return this.delegate.getBody();
}
 
Example 5
Source File: FormHttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage)
		throws IOException {

	final byte[] boundary = generateMultipartBoundary();
	Map<String, String> parameters = new LinkedHashMap<>(2);
	if (!isFilenameCharsetSet()) {
		parameters.put("charset", this.charset.name());
	}
	parameters.put("boundary", new String(boundary, StandardCharsets.US_ASCII));

	MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
	HttpHeaders headers = outputMessage.getHeaders();
	headers.setContentType(contentType);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> {
			writeParts(outputStream, parts, boundary);
			writeEnd(outputStream, boundary);
		});
	}
	else {
		writeParts(outputMessage.getBody(), parts, boundary);
		writeEnd(outputMessage.getBody(), boundary);
	}
}
 
Example 6
Source File: FormHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void writeMultipart(final MultiValueMap<String, Object> parts, HttpOutputMessage outputMessage) throws IOException {
	final byte[] boundary = generateMultipartBoundary();
	Map<String, String> parameters = Collections.singletonMap("boundary", new String(boundary, "US-ASCII"));

	MediaType contentType = new MediaType(MediaType.MULTIPART_FORM_DATA, parameters);
	HttpHeaders headers = outputMessage.getHeaders();
	headers.setContentType(contentType);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
			@Override
			public void writeTo(OutputStream outputStream) throws IOException {
				writeParts(outputStream, parts, boundary);
				writeEnd(outputStream, boundary);
			}
		});
	}
	else {
		writeParts(outputMessage.getBody(), parts, boundary);
		writeEnd(outputMessage.getBody(), boundary);
	}
}
 
Example 7
Source File: BodyExtractors.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Extractor to read multipart data into {@code Flux<Part>}.
 * @return {@code BodyExtractor} for multipart request parts
 */
// Parameterized for server-side use
public static BodyExtractor<Flux<Part>, ServerHttpRequest> toParts() {
	return (serverRequest, context) -> {
		ResolvableType elementType = PART_TYPE;
		MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
		HttpMessageReader<Part> reader = findReader(elementType, mediaType, context);
		return readToFlux(serverRequest, context, elementType, reader);
	};
}
 
Example 8
Source File: ClientHttpRequest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to determine the content/media type of this HTTP request iff the HTTP "Content-Type" header was not
 * explicitly set by the user, otherwise the user provided value is used.  If the "Content-Type" HTTP header value
 * is null, then the content/media/payload of this HTTP request is inspected to determine the content type.
 * <p/>
 * The simplest evaluation sets the content type to "application/x-www-form-urlencoded" if this is a POST or PUT
 * HTTP request, unless any request parameter value is determined to have multiple parts, the the content type will be
 * "multipart/form-data".
 * <p/>
 * @param defaultContentType the default content/media type to use when the content type cannot be determined from
 * this HTTP request.
 * @return a MediaType for the value of the HTTP Content-Type header as determined from this HTTP request.
 * @see #getHeaders()
 * @see org.springframework.http.HttpHeaders#getContentType()
 * @see org.springframework.http.MediaType
 */
protected MediaType determineContentType(final MediaType defaultContentType) {
  MediaType contentType = getHeaders().getContentType();

  // if the content type HTTP header was not explicitly set, try to determine the media type from the content body
  // of the HTTP request
  if (contentType == null) {
    if (isPost() || isPut()) {
      OUT : for (final String name : getParameters().keySet()) {
        for (final Object value : getParameters().get(name)) {
          if (value != null && !(value instanceof String)) {
            contentType = MediaType.MULTIPART_FORM_DATA;
            break OUT;
          }
        }
      }

      // since this is a POST/PUT HTTP request, default the content/media type to "application/x-www-form-urlencoded"
      contentType = ObjectUtils.defaultIfNull(contentType, MediaType.APPLICATION_FORM_URLENCODED);
    }
    else {
      // NOTE the "Content-Type" HTTP header is not applicable to GET/DELETE and other methods of HTTP requests
      // since there is typically no content (media/payload/request body/etc) to send.  Any request parameters
      // are encoded in the URL as query parameters.
    }
  }

  return ObjectUtils.defaultIfNull(contentType, defaultContentType);
}
 
Example 9
Source File: ClientHttpRequest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Tries to determine the content/media type of this HTTP request iff the HTTP "Content-Type" header was not
 * explicitly set by the user, otherwise the user provided value is used.  If the "Content-Type" HTTP header value
 * is null, then the content/media/payload of this HTTP request is inspected to determine the content type.
 * <p/>
 * The simplest evaluation sets the content type to "application/x-www-form-urlencoded" if this is a POST or PUT
 * HTTP request, unless any request parameter value is determined to have multiple parts, the the content type will be
 * "multipart/form-data".
 * <p/>
 * @param defaultContentType the default content/media type to use when the content type cannot be determined from
 * this HTTP request.
 * @return a MediaType for the value of the HTTP Content-Type header as determined from this HTTP request.
 * @see #getHeaders()
 * @see org.springframework.http.HttpHeaders#getContentType()
 * @see org.springframework.http.MediaType
 */
protected MediaType determineContentType(final MediaType defaultContentType) {
  MediaType contentType = getHeaders().getContentType();

  // if the content type HTTP header was not explicitly set, try to determine the media type from the content body
  // of the HTTP request
  if (contentType == null) {
    if (isPost() || isPut()) {
      OUT : for (final String name : getParameters().keySet()) {
        for (final Object value : getParameters().get(name)) {
          if (value != null && !(value instanceof String)) {
            contentType = MediaType.MULTIPART_FORM_DATA;
            break OUT;
          }
        }
      }

      // since this is a POST/PUT HTTP request, default the content/media type to "application/x-www-form-urlencoded"
      contentType = ObjectUtils.defaultIfNull(contentType, MediaType.APPLICATION_FORM_URLENCODED);
    }
    else {
      // NOTE the "Content-Type" HTTP header is not applicable to GET/DELETE and other methods of HTTP requests
      // since there is typically no content (media/payload/request body/etc) to send.  Any request parameters
      // are encoded in the URL as query parameters.
    }
  }

  return ObjectUtils.defaultIfNull(contentType, defaultContentType);
}
 
Example 10
Source File: BodyExtractors.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Extractor to read multipart data into {@code Flux<Part>}.
 * @return {@code BodyExtractor} for multipart request parts
 */
// Parameterized for server-side use
public static BodyExtractor<Flux<Part>, ServerHttpRequest> toParts() {
	return (serverRequest, context) -> {
		ResolvableType elementType = PART_TYPE;
		MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
		HttpMessageReader<Part> reader = findReader(elementType, mediaType, context);
		return readToFlux(serverRequest, context, elementType, reader);
	};
}
 
Example 11
Source File: BodyExtractors.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Extractor to read multipart data into a {@code MultiValueMap<String, Part>}.
 * @return {@code BodyExtractor} for multipart data
 */
// Parameterized for server-side use
public static BodyExtractor<Mono<MultiValueMap<String, Part>>, ServerHttpRequest> toMultipartData() {
	return (serverRequest, context) -> {
		ResolvableType elementType = MULTIPART_DATA_TYPE;
		MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
		HttpMessageReader<MultiValueMap<String, Part>> reader = findReader(elementType, mediaType, context);
		return readToMono(serverRequest, context, elementType, reader);
	};
}
 
Example 12
Source File: BodyExtractors.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Extractor to read multipart data into a {@code MultiValueMap<String, Part>}.
 * @return {@code BodyExtractor} for multipart data
 */
// Parameterized for server-side use
public static BodyExtractor<Mono<MultiValueMap<String, Part>>, ServerHttpRequest> toMultipartData() {
	return (serverRequest, context) -> {
		ResolvableType elementType = MULTIPART_DATA_TYPE;
		MediaType mediaType = MediaType.MULTIPART_FORM_DATA;
		HttpMessageReader<MultiValueMap<String, Part>> reader = findReader(elementType, mediaType, context);
		return readToMono(serverRequest, context, elementType, reader);
	};
}
 
Example 13
Source File: MockMultipartHttpServletRequestBuilder.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Package-private constructor. Use static factory methods in
 * {@link MockMvcRequestBuilders}.
 * <p>For other ways to initialize a {@code MockMultipartHttpServletRequest},
 * see {@link #with(RequestPostProcessor)} and the
 * {@link RequestPostProcessor} extension point.
 * @param uri the URL
 * @since 4.0.3
 */
MockMultipartHttpServletRequestBuilder(URI uri) {
	super(HttpMethod.POST, uri);
	super.contentType(MediaType.MULTIPART_FORM_DATA);
}
 
Example 14
Source File: MockMultipartHttpServletRequestBuilder.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Package-private constructor. Use static factory methods in
 * {@link MockMvcRequestBuilders}.
 * <p>For other ways to initialize a {@code MockMultipartHttpServletRequest},
 * see {@link #with(RequestPostProcessor)} and the
 * {@link RequestPostProcessor} extension point.
 * @param urlTemplate a URL template; the resulting URL will be encoded
 * @param uriVariables zero or more URI variables
 */
MockMultipartHttpServletRequestBuilder(String urlTemplate, Object... uriVariables) {
	super(HttpMethod.POST, urlTemplate, uriVariables);
	super.contentType(MediaType.MULTIPART_FORM_DATA);
}
 
Example 15
Source File: MockMultipartHttpServletRequestBuilder.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Package-private constructor. Use static factory methods in
 * {@link MockMvcRequestBuilders}.
 * <p>For other ways to initialize a {@code MockMultipartHttpServletRequest},
 * see {@link #with(RequestPostProcessor)} and the
 * {@link RequestPostProcessor} extension point.
 * @param urlTemplate a URL template; the resulting URL will be encoded
 * @param urlVariables zero or more URL variables
 */
MockMultipartHttpServletRequestBuilder(String urlTemplate, Object... urlVariables) {
	super(HttpMethod.POST, urlTemplate, urlVariables);
	super.contentType(MediaType.MULTIPART_FORM_DATA);
}
 
Example 16
Source File: MockMultipartHttpServletRequestBuilder.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Package-private constructor. Use static factory methods in
 * {@link MockMvcRequestBuilders}.
 * <p>For other ways to initialize a {@code MockMultipartHttpServletRequest},
 * see {@link #with(RequestPostProcessor)} and the
 * {@link RequestPostProcessor} extension point.
 * @param uri the URL
 * @since 4.0.3
 */
MockMultipartHttpServletRequestBuilder(URI uri) {
	super(HttpMethod.POST, uri);
	super.contentType(MediaType.MULTIPART_FORM_DATA);
}
 
Example 17
Source File: MockMultipartHttpServletRequestBuilder.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Package-private constructor. Use static factory methods in
 * {@link MockMvcRequestBuilders}.
 * <p>For other ways to initialize a {@code MockMultipartHttpServletRequest},
 * see {@link #with(RequestPostProcessor)} and the
 * {@link RequestPostProcessor} extension point.
 * @param uri the URL
 * @since 4.0.3
 */
MockMultipartHttpServletRequestBuilder(URI uri) {
	super(HttpMethod.POST, uri);
	super.contentType(MediaType.MULTIPART_FORM_DATA);
}
 
Example 18
Source File: MockMultipartHttpServletRequestBuilder.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Package-private constructor. Use static factory methods in
 * {@link MockMvcRequestBuilders}.
 * <p>For other ways to initialize a {@code MockMultipartHttpServletRequest},
 * see {@link #with(RequestPostProcessor)} and the
 * {@link RequestPostProcessor} extension point.
 * @param urlTemplate a URL template; the resulting URL will be encoded
 * @param uriVariables zero or more URI variables
 */
MockMultipartHttpServletRequestBuilder(String urlTemplate, Object... uriVariables) {
	super(HttpMethod.POST, urlTemplate, uriVariables);
	super.contentType(MediaType.MULTIPART_FORM_DATA);
}