public FormOAuth2AccessTokenMessageConverter() { super(MediaType.APPLICATION_FORM_URLENCODED, MediaType.TEXT_PLAIN); this.delegateMessageConverter = new FormHttpMessageConverter(); }
private MultiValueMap<String, String> parseFormData(final MediaType mediaType) { HttpInputMessage message = new HttpInputMessage() { @Override public InputStream getBody() { return (content != null ? new ByteArrayInputStream(content) : StreamUtils.emptyInput()); } @Override public HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(mediaType); return headers; } }; try { return new FormHttpMessageConverter().read(null, message); } catch (IOException ex) { throw new IllegalStateException("Failed to parse form data in request body", ex); } }
/** * The default character set to use for reading form data. * This is a shortcut for:<br> * {@code getFormConverter.setCharset(charset)}. */ public void setCharset(Charset charset) { this.formConverter.setCharset(charset); }
@SuppressWarnings("unchecked") private void writePart(String name, HttpEntity<?> partEntity, OutputStream os) throws IOException { Object partBody = partEntity.getBody(); if (partBody == null) { throw new IllegalStateException("Empty body for part '" + name + "': " + partEntity); } Class<?> partType = partBody.getClass(); HttpHeaders partHeaders = partEntity.getHeaders(); MediaType partContentType = partHeaders.getContentType(); for (HttpMessageConverter<?> messageConverter : this.partConverters) { if (messageConverter.canWrite(partType, partContentType)) { Charset charset = isFilenameCharsetSet() ? StandardCharsets.US_ASCII : this.charset; HttpOutputMessage multipartMessage = new MultipartHttpOutputMessage(os, charset); multipartMessage.getHeaders().setContentDispositionFormData(name, getFilename(partBody)); if (!partHeaders.isEmpty()) { multipartMessage.getHeaders().putAll(partHeaders); } ((HttpMessageConverter<Object>) messageConverter).write(partBody, partContentType, multipartMessage); return; } } throw new HttpMessageNotWritableException("Could not write request: no suitable HttpMessageConverter " + "found for request type [" + partType.getName() + "]"); }
@Test public void multipartFileResource() throws IOException { String name = "file"; String disposition = "form-data; name=\"" + name + "\"; filename=\"myFile.txt\""; StandardMultipartHttpServletRequest request = requestWithPart(name, disposition, "myBody"); MultipartFile multipartFile = request.getFile(name); assertNotNull(multipartFile); MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); map.add(name, multipartFile.getResource()); MockHttpOutputMessage output = new MockHttpOutputMessage(); new FormHttpMessageConverter().write(map, null, output); assertThat(output.getBodyAsString(StandardCharsets.UTF_8), containsString( "Content-Disposition: form-data; name=\"file\"; filename=\"myFile.txt\"\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: 6\r\n" + "\r\n" + "myBody\r\n")); }
/** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; }
@Nullable private MultiValueMap<String, String> parseIfNecessary(HttpServletRequest request) throws IOException { if (!shouldParse(request)) { return null; } HttpInputMessage inputMessage = new ServletServerHttpRequest(request) { @Override public InputStream getBody() throws IOException { return request.getInputStream(); } }; return this.formConverter.read(null, inputMessage); }
/** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); return converter; }
@Produces public RestTemplate getRestTemplate() { RestTemplate template = new RestTemplate(); template.getMessageConverters().add(0,createFormHttpConverter()); return template; } private static HttpMessageConverter<?> createFormHttpConverter(){ FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); formHttpMessageConverter.setPartConverters(getPartConverters()); return formHttpMessageConverter; } private static List<HttpMessageConverter<?>> getPartConverters(){ RestTemplate template = new RestTemplate(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); List<HttpMessageConverter<?>> messageConverters = template.getMessageConverters(); messageConverters.add(0,converter); return messageConverters; }
public void write(OAuth2Exception t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>(); data.add(OAuth2Exception.ERROR, t.getOAuth2ErrorCode()); data.add(OAuth2Exception.DESCRIPTION, t.getMessage()); Map<String, String> additionalInformation = t.getAdditionalInformation(); if(additionalInformation != null) { for(Map.Entry<String,String> entry : additionalInformation.entrySet()) { data.add(entry.getKey(), entry.getValue()); } } delegateMessageConverter.write(data, contentType, outputMessage); }
HttpMessageConverter<Object> jackson = new MappingJackson2HttpMessageConverter(); HttpMessageConverter<Resource> resource = new ResourceHttpMessageConverter(); FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); formHttpMessageConverter.addPartConverter(jackson); formHttpMessageConverter.addPartConverter(resource); // This is hope driven programming RestTemplate restTemplate = new RestTemplate(Arrays.asList(jackson, resource, formHttpMessageConverter));
@Override public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) { if (!MultiValueMap.class.isAssignableFrom(clazz)) { return false; } if (mediaType == null || MediaType.ALL.equals(mediaType)) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { if (supportedMediaType.isCompatibleWith(mediaType)) { return true; } } return false; }
private FormHttpMessageConverter getFormHttpMessageConverter() { FormHttpMessageConverter formPartsMessageConverter = new CloudFoundryFormHttpMessageConverter(); formPartsMessageConverter.setPartConverters(getFormPartsMessageConverters()); return formPartsMessageConverter; }
this.converter.setMultipartCharset(StandardCharsets.UTF_8); this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);
@Override protected String getFilename(Object part) { if (part instanceof UploadApplicationPayload) { return ((UploadApplicationPayload) part).getArchive().getFilename(); } return super.getFilename(part); } }
/** * Returns an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. * By default, the message converter is set to use "UTF-8" character encoding. * Override to customize the message converter (for example, to set supported media types or message converters for the parts of a multipart message). * To remove/replace this or any of the other message converters that are registered by default, override the getMessageConverters() method instead. * @return an {@link FormHttpMessageConverter} to be used by the internal {@link RestTemplate}. */ protected FormHttpMessageConverter getFormMessageConverter() { FormHttpMessageConverter converter = new FormHttpMessageConverter(); converter.setCharset(Charset.forName("UTF-8")); List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>(); partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8")); stringHttpMessageConverter.setWriteAcceptCharset(false); partConverters.add(stringHttpMessageConverter); partConverters.add(new ResourceHttpMessageConverter()); converter.setPartConverters(partConverters); return converter; }
@Override protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (("PUT".equals(request.getMethod()) || "PATCH".equals(request.getMethod())) && isFormContentType(request)) { HttpInputMessage inputMessage = new ServletServerHttpRequest(request) { @Override public InputStream getBody() throws IOException { return request.getInputStream(); } }; MultiValueMap<String, String> formParameters = this.formConverter.read(null, inputMessage); if (!formParameters.isEmpty()) { HttpServletRequest wrapper = new HttpPutFormContentRequestWrapper(request, formParameters); filterChain.doFilter(wrapper, response); return; } } filterChain.doFilter(request, response); }
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); formHttpMessageConverter.setCharset(Charset.forName("UTF8")); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(formHttpMessageConverter); restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); restTemplate.setInterceptors(Arrays.asList(new LoggingRequestInterceptor())); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); String uri = "https://if-one.pl/api/v1/documents"; String imagePath = "/path_to_file/do1.jpg"; String imagePath2 = "/path_to_file/do2.jpg"; MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); map.add("doctype", "idcard"); Resource file1 = new FileSystemResource(imagePath); Resource file2 = new FileSystemResource(imagePath2); map.add("file", file1); map.add("file", file1); HttpHeaders imageHeaders = createHeaders(); imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, imageHeaders); HttpEntity<String> request = new HttpEntity<String>(imageHeaders); ResponseEntity<String> resposne = restTemplate.exchange(uri, HttpMethod.POST, imageEntity, String.class);
public void doWithRequest(ClientHttpRequest request) throws IOException { request.getHeaders().putAll(this.headers); request.getHeaders().setAccept( Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED)); if (logger.isDebugEnabled()) { logger.debug("Encoding and sending form: " + form); } FORM_MESSAGE_CONVERTER.write(this.form, MediaType.APPLICATION_FORM_URLENCODED, request); } }
@Override public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) { if (!MultiValueMap.class.isAssignableFrom(clazz)) { return false; } if (mediaType == null) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { // We can't read multipart.... if (!supportedMediaType.equals(MediaType.MULTIPART_FORM_DATA) && supportedMediaType.includes(mediaType)) { return true; } } return false; }