是否可以使用 jax-rs POST 方法发送两种不同的 Content-Type 来下载文件
Is it possible to send two different Content-Type for downloading file using jax-rs POST method
是否可以使用 post-man 为 POST 方法发送两种不同的 Content-Type?比如,如果该服务用于下载 excel 文件,那么在这种情况下,@Consumes(MediaType.APPLICATION_JSON)
用于发送一些用户详细信息,即 json 结构,@Produces(MediaType.APPLICATION_OCTET_STREAM)
用于发送将响应作为文件返回。
注意:我不想使用表单数据,这是此服务的一个限制条件。
根据客户端请求,Content-Type
header is only for the type of data that is in the entity body. The Accept
header 是您发送的数据类型。
在服务器端,执行以下操作完全没问题。
@POST
@Path("something")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response post(Model model) throws Exception {
final InputStream in = new FileInputStream("path-to-file");
StreamingOutput entity = new StreamingOutput() {
@Override
public void write(OutputStream out) {
IOUtils.copy(in, out);
out.flush();
}
};
return Response.ok(entity)
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=somefile.xls")
.build();
}
对该端点的请求应该类似于
POST /api/something HTTP 1.1
Content-Type: application/json;charset=utf-8
Accept: application/octet-stream
{"the":"json", "entity":"body"}
另请参阅:
- This post 关于
@Produces
和 @Consumes
的目的以及它们在内容协商中扮演的角色。
放在一边
顺便说一句,考虑使用 application/vnd.ms-excel
作为 Content-Type
而不是 application/octet-stream
。这已经是 Microsoft Excel files1 的标准 MIME 类型。当使用 StreamingOutput
作为响应实体类型时,您可以将 @Produces
设为任何您想要的,因为不需要真正的转换。
在Postman中,当你使用"Send and download"功能时,你会注意到当Content-Type
为application/octet-stream
时,它会提示.bin
的文件扩展名保存文件。但是,如果您将 Content-Type
作为 application/vnd.ms-excel
,那么建议的扩展名是 .xls
,这是应该的。
是否可以使用 post-man 为 POST 方法发送两种不同的 Content-Type?比如,如果该服务用于下载 excel 文件,那么在这种情况下,@Consumes(MediaType.APPLICATION_JSON)
用于发送一些用户详细信息,即 json 结构,@Produces(MediaType.APPLICATION_OCTET_STREAM)
用于发送将响应作为文件返回。
注意:我不想使用表单数据,这是此服务的一个限制条件。
根据客户端请求,Content-Type
header is only for the type of data that is in the entity body. The Accept
header 是您发送的数据类型。
在服务器端,执行以下操作完全没问题。
@POST
@Path("something")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response post(Model model) throws Exception {
final InputStream in = new FileInputStream("path-to-file");
StreamingOutput entity = new StreamingOutput() {
@Override
public void write(OutputStream out) {
IOUtils.copy(in, out);
out.flush();
}
};
return Response.ok(entity)
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=somefile.xls")
.build();
}
对该端点的请求应该类似于
POST /api/something HTTP 1.1
Content-Type: application/json;charset=utf-8
Accept: application/octet-stream
{"the":"json", "entity":"body"}
另请参阅:
- This post 关于
@Produces
和@Consumes
的目的以及它们在内容协商中扮演的角色。
放在一边
顺便说一句,考虑使用 application/vnd.ms-excel
作为 Content-Type
而不是 application/octet-stream
。这已经是 Microsoft Excel files1 的标准 MIME 类型。当使用 StreamingOutput
作为响应实体类型时,您可以将 @Produces
设为任何您想要的,因为不需要真正的转换。
在Postman中,当你使用"Send and download"功能时,你会注意到当Content-Type
为application/octet-stream
时,它会提示.bin
的文件扩展名保存文件。但是,如果您将 Content-Type
作为 application/vnd.ms-excel
,那么建议的扩展名是 .xls
,这是应该的。