当前位置: 首页 > 知识库问答 >
问题:

带有Resttemplate的ByteArrayInputStream

云星波
2023-03-14

我需要将ByteArrayInputStream传递到web层。在ByteArrayInputStream形成后,我通过RestController传递到serviceRest,然后传递到web层。

我将对象导出到。xlsx和return ByteArrayInputStream

@Override
    public  ByteArrayInputStream exportProjectsToExcel(List<Projects> projectsList) {


        try {
            Workbook workbook = new XSSFWorkbook();

            Sheet sheet = workbook.createSheet("projects");

            Row row = sheet.createRow(0);

            CellStyle headerSellStyle = cellStyle(workbook, IndexedColors.SKY_BLUE);

            Cell cell = row.createCell(0);
            cell.setCellValue("projectId");
            cell.setCellStyle(headerSellStyle);

            cell = row.createCell(1);
            cell.setCellValue("description");
            cell.setCellStyle(headerSellStyle);

            cell = row.createCell(2);
            cell.setCellValue("dateAdded");
            cell.setCellStyle(headerSellStyle);

            for (int i = 0; i < projectsList.size(); i++) {

                Row dataRow = sheet.createRow(i + 1);
                CellStyle bodySellStyle = cellStyle(workbook, IndexedColors.WHITE);

                Cell bodyCell = dataRow.createCell(0);
                bodyCell.setCellValue(projectsList.get(i).getProjectId());
                bodyCell.setCellStyle(bodySellStyle);

                bodyCell = dataRow.createCell(1);
                bodyCell.setCellValue(projectsList.get(i).getDescription());
                bodyCell.setCellStyle(bodySellStyle);

                bodyCell = dataRow.createCell(2);
                bodyCell.setCellValue(projectsList.get(i).getDateAdded().toString());
                bodyCell.setCellStyle(bodySellStyle);
            }
            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);

            return new ByteArrayInputStream(outputStream.toByteArray());

        } catch (IOException e) {
            e.printStackTrace();

            return null;
        }
    }

然后我需要通过RestController传递ByteArrayInputStream

 @PostMapping(value = "/projectsDownload")
    public ByteArrayInputStream downloadExcelProjects( @RequestBody (required = false) List<Projects> projectsList) throws IOException {

        LOGGER.debug("**************************************************{}", projectsList);

        ByteArrayInputStream stream = excelFileExportService.exportProjectsToExcel(projectsList);

        return stream;
    }


使用resttemplate访问serviceRest

 @Override
    public ByteArrayInputStream exportProjectsToExcel(List<Projects> projectsList) {

        LOGGER.debug("////////////////////////////////////////////////exportProjectsToExcel({})", projectsList);

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.ALL));
        HttpEntity<List> entity = new HttpEntity<>(projectsList, headers);
        ResponseEntity<ByteArrayInputStream> result = restTemplate.postForEntity(url + "/projectsDownload", entity, ByteArrayInputStream.class);
        return result.getBody();
    }

但我有以下例外

19:52:15 [http-nio-8088-exec-9] DEBUG c.e.b.c.r.c.DownloadExcelProjectsController - **************************************************[Projects(projectId=1, description=Create a web application based on SpringJDBC, dateAdded=2019-07-15, fileType=null, multipartFile=null, developers=null), Projects(projectId=2, description=Create a web application based on SpringBoot, dateAdded=2019-08-13, fileType=null, multipartFile=null, developers=null), Projects(projectId=3, description=Create a web application based on Hibernate, dateAdded=2020-01-17, fileType=null, multipartFile=null, developers=null)]
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Using @ExceptionHandler com.epam.brest.courses.rest_app.exception.CustomExceptionHandler#handleException(Exception, WebRequest)
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - No match for [*/*], supported: []
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.io.ByteArrayInputStream]
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.o.j.s.OpenEntityManagerInViewInterceptor - Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.DispatcherServlet - Completed 500 INTERNAL_SERVER_ERROR

如果有任何帮助,我将不胜感激。谢谢

共有1个答案

严繁
2023-03-14

您可以将其转换为资源对象,Spring在编写对象时无法转换Bytearrayinputstream,rest模板也无法通过简单地传递inputstream来读取它。

试试这段代码:

Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);




File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
    File ret = File.createTempFile("download", "tmp");
    StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
    return ret;
});
 

 类似资料:
  • 我们的RESTAPI将返回页面中的结果。下面是一个控制器的示例 有没有一个简单的方法来消耗该API与重新设置模板? 如果我们这样做 它抛出一个异常 先谢谢你

  • 我需要发送一个GET请求,标题是:。我期待服务器的XML响应。我用邮递员测试了请求和响应,一切都很好。但是,当我尝试在Spring中使用执行此操作时,我总是会收到400个错误请求。的异常是: 我的代码: 调试消息将标头显示为,这似乎是正确的。我想知道我的请求出了什么问题,以及是否有一种方法可以看到在线调试的请求。

  • 我是Spring的新手,正在尝试用RestTemplate执行rest请求。Java代码应该执行与下面curl命令相同的操作: 但服务器拒绝了带有的RestTemplate

  • 问题内容: 我有带私钥和服务器证书的pem证书。我可以使用curl执行它,一切正常。 但是我想将其与Java一起使用,最可取的是从Spring开始的RestTemplate。 问题答案: 因此,将有关与RestTemplate一起使用pem证书的知识分散了。 必须完成的步骤: 使用keytool或portecle将服务器证书添加到trustStore。当您要使用自定义信任关系时,请使用此脚本 接下

  • 我意识到我试图创建的项目中有一些有线的东西。我正在使用RestTemplate。我正在尝试连接服务器并检索数据。一切都很顺利,直到我决定在多个控制器类中破坏我的程序。看看我做了什么。在这些新类别中,我在每个类别中插入: 为了检索数据,我只使用JAXB注释(用于数据绑定),我可以检索我想要的任何东西。但是当我尝试在新类中执行这行代码时: 我接受这个例外:RestClientException“无法提