Spring RestTemplate-服务器中的文件意外结束;嵌套的异常是java.net.SocketException:服务器中的文件意外结束

时间:2019-11-27 18:48:50

标签: spring resttemplate

尝试通过resttemplate将照片作为字节数组发送,并收到“来自服务器的文件意外结束;嵌套的异常是java.net.SocketException:来自服务器的文件意外结束”。 所有错误 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

但是,如果我发送的这个数组没有结束字节,则发送成功。 我的代码:

    @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();
            }
        }
    } ```

1 个答案:

答案 0 :(得分:0)

在Google中只有一个简单的请求以及所有第一个链接都显示了正确的方式:

使用MediaType.MULTIPART_FORM_DATAResponseEntity<String>