首页 > 解决方案 > Spring resttemplate - 来自服务器的文件意外结束;嵌套异常是 java.net.SocketException: Unexpected end of file from server

问题描述

尝试通过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();
            }
        }
    } ```

标签: springresttemplate

解决方案


谷歌中只有一个简单的请求,所有第一个链接都显示了正确的方法:

使用MediaType.MULTIPART_FORM_DATAResponseEntity<String>


推荐阅读