java - 无法创建生成的 HTTP 客户端所需的返回类型,因为没有从 ByteBuffer 到类 java.io.File : Micronaut 的 TypeConverter

标签 java rest http micronaut micronaut-client

下面是使用 micronaut 将文件作为 rest 响应发送到客户端的服务器端代码。

@Get(value = "/downloadFile", produces = MediaType.APPLICATION_OCTET_STREAM )
public HttpResponse<File> downloadDocument() throws IOException {

    File sampleDocumentFile = new File(getClass().getClassLoader().getResource("SampleDocument.pdf").getFile());

    return HttpResponse.ok(sampleDocumentFile).header("Content-Disposition", "attachment; filename=\"" + sampleDocumentFile.getName() + "\"" );
}

下面是调用上述端点的客户端。

@Client(value = "/client")
public interface DownloadDocumentClient {

@Get(value = "/downloadDocument", processes = MediaType.APPLICATION_OCTET_STREAM)
public Flowable<File> downloadDocument();

}

尝试如下检索文件:-

Flowable<File> fileFlowable = downloadDocumentClient.downloadDocument();
    Maybe<File> fileMaybe = fileFlowable.firstElement();
    return fileMaybe.blockingGet();

获取异常为

io.micronaut.context.exceptions.ConfigurationException: Cannot create the generated HTTP client's required return type, since no TypeConverter from ByteBuffer to class java.io.File is registered

最佳答案

您不能使用 File 实例发送文件数据,因为它只包含路径而不包含文件内容。您可以使用字节数组发送文件内容。

以这种方式更新 Controller :

@Get(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM)
public HttpResponse<byte[]> downloadDocument() throws IOException, URISyntaxException {
    String documentName = "SampleDocument.pdf";
    byte[] content = Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(documentName).toURI()));
    return HttpResponse.ok(content).header("Content-Disposition", "attachment; filename=\"" + documentName + "\"");
}

客户端会变成这样:

@Get(value = "/download", processes = MediaType.APPLICATION_OCTET_STREAM)
Flowable<byte[]> downloadDocument();

最后是客户电话:

Flowable<byte[]> fileFlowable = downloadDocumentClient.downloadDocument();
Maybe<byte[]> fileMaybe = fileFlowable.firstElement();
byte[] content = fileMaybe.blockingGet();

更新: 如果您需要将接收到的字节(文件内容)保存到客户端计算机(容器)上的文件中,那么您可以这样做,例如:

Path targetPath = Files.write(Paths.get("target.pdf"), fileMaybe.blockingGet());

如果您真的需要 File 实例而不是 Path 来进行进一步处理,那么只需:

File file = targetPath.toFile();

关于java - 无法创建生成的 HTTP 客户端所需的返回类型,因为没有从 ByteBuffer 到类 java.io.File : Micronaut 的 TypeConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58202845/

相关文章:

java - 如何在 jenkinsfile 中将参数传递给 sbt

java - EclipseLink - 合并更新尚未更改的列

java - var-args 只能用作方法参数吗?

php - jira rest api 在创建问题时出错

java - 尝试从文档检索 Java 中的节点值时出错

java - 加载 java native 文件库

ruby-on-rails - ExtJs4 json data.store 和 Rails

php - 从 Java 执行许多(顺序的)HTTP POST 命令到 PHP 文件时出现服务器异常

用于处理 session 、cookie、post/get、keep-alive 和异步的 Android HTTP 库

php - HTTP Header Referrer 使用 PHP 作弊