I have a method which calls an external service using Spring's RestTemplate:
public SomeClass methodThatCallsAnExternalService(String id, String fileName, byte[] file) throws IOException {
Resource resourceFile = new FileSystemResource(file, fileName);
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "multipart/form-data; charset=utf-8");
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("id", id);
body.add("inputFile", resourceFile);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
return objectMapper.readValue(response.getBody(), SomeClass.class);
}
and the FileSystemResource
is defined as follows:
private static class FileSystemResource extends ByteArrayResource {
private String fileName;
public FileSystemResource(byte[] byteArray, String filename) {
super(byteArray);
this.fileName = filename;
}
public String getFilename() {
return fileName;
}
public void setFilename(String fileName) {
this.fileName = fileName;
}
}
This works as it should in most cases, but if the fileName
argument contains special characters such as õäöü, the RestTemplate request fails and the only response given is
org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.logException - Resolved [org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 Internal Server Error: [<!DOCTYPE html>
<html lang="en">
<head>
<title>Execution exception</title>
<link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXR... (7772 bytes)]]
How can I make the RestTemplate accept special characters? As can be seen, I have already tried specifying charset in a header and adding a new message converter, but neither worked.