0

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.

Florian
  • 3
  • 3
  • The problem can be in the server side. – pringi Mar 07 '22 at 16:36
  • Do you mean the external service where the call is made? If you do then no, because the external service is used for the same purpose in other applications, all of which handle the special characters correctly. – Florian Mar 07 '22 at 17:05
  • You could try a slightly different approach as shown at https://stackoverflow.com/a/63650486/3080094 – vanOekel Mar 07 '22 at 21:09
  • Cannot use that approach because the external service does not accept requests in that format and I have no ability to do necessary modifications so it would accept. – Florian Mar 08 '22 at 08:15

0 Answers0