Search code examples
springresttemplate

Spring resttemplate - Unexpected end of file from server; nested exception is java.net.SocketException: Unexpected end of file from server


Try sent photo as byte array through resttemplate and receive "Unexpected end of file from server; nested exception is java.net.SocketException: Unexpected end of file from server". All errors org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://servername12:8091/rs/photo": Unexpected end of file from server; nested exception is java.net.SocketException: Unexpected end of file from server

However, if I sent this array without end byte it send successful. My code:

    @ResponseBody
    public void uploadFile(@RequestParam("file") MultipartFile file)
    {
        if (!file.isEmpty()) {
            try
            {
                byte[] bytes = file.getBytes();
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentLength(1000000000);
                HttpEntity<byte[]> entity = new HttpEntity<>(bytes, headers);
                RestTemplate restTemplate = new RestTemplate();

                ResponseEntity<ValidatorResponse> response = restTemplate.postForEntity(VALIDATOR_URL + "photo", bytes, ValidatorResponse.class);
                System.out.println(response.getBody().getCode());

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    } ```

Solution

  • Just one simple request in Google and all first links show the proper way:

    Use MediaType.MULTIPART_FORM_DATA and ResponseEntity<String>