Spring RestTemplate filename with accents

2.1k Views Asked by At

I have a problem uploading a file with Spring RestTemplate. If the file contains characters with an accent, the original filename is not encoded correctly and not sent over the wire correctly. The characters with an accent are displayed with a question mark on the server.

If I use Postman or Advanced Rest Client, it works. When sniffing using wireshark, I can see that both tools encode the filename differently. Anybody got an idea on how to make RestTemplate handle accents in filenames correctly?

Below is the code I am using to call my webservice endpoint.

final String fileName = "Sécurité report.pdf";
final LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(fileName));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

final HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);

final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<String> result = restTemplate.exchange("http://localhost:8080", HttpMethod.POST, requestEntity, String.class);
2

There are 2 best solutions below

1
On

You need to add a UTF-8 message converter to the RestTemplate

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
    .add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

See also: How can I tell RestTemplate to POST with UTF-8 encoding?

4
On

Configure your RestTemplate with custom FormHttpMessageConverter instance with property multipartCharset set to UTF-8.

FormHttpMessageConverter converter = new FormHttpMessageConverter();
converter.setMultipartCharset(Charset.forName("UTF-8"));