【问题标题】:Rest API with both Json and a csv file as attachment以 Json 和 csv 文件作为附件的 Rest API
【发布时间】:2019-12-18 14:46:57
【问题描述】:

我们能否在 Rest Service 中同时提供 Json 响应和 csv 文件作为附件?

我已经编写了如下代码,但我也确信它不会工作。

            ResponseBuilder responseBuilder = null;
        responseBuilder = Response.status(200).type(MediaType.APPLICATION_JSON)
                .entity(parseOrganizations(getOrganizationsResponseMashery(limit, offset)));
         responseBuilder.type(MediaType.TEXT_PLAIN).entity(file).header("Content-Disposition", "attachment; filename=Organizations.csv");
        return responseBuilder.build();

带有文件的实体的第二个设置器,基本上覆盖了我之前作为实体插入的 json 内容。所以请建议。

【问题讨论】:

  • 我认为下面的solution 是你要找的。​​span>

标签: java rest spring-boot response spring-jersey


【解决方案1】:

是的,没错,HTTP 响应应该是单一类型的。如果您告诉您返回 JSON,那么客户端将期待 JSON 对象,而不是文件。同样,如果你说你返回一个文件,它会期待一个文件。

客户端将根据响应标头中声明的返回类型采取行动(例如:将 JSON 对象映射到类实例等),因此明确这一点很重要。

在 springboot 的情况下,似乎最后一次调用 type 方法会覆盖之前的调用。

【讨论】:

  • HTTP 响应类型也有“multipart_mixed”对吗?那么无论如何我们可以使用它来实现这个场景。
  • 是的,但正如所指出的,并非所有客户端都会处理它。我的印象是它因此而气馁。见stackoverflow.com/questions/50188321/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-29
  • 2019-01-12
  • 1970-01-01
  • 2013-01-03
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多