Java RESTful生成二进制文件
我是使用CXF和Spring创建RESTful Web服务的新手 这就是我的问题:我想创建一个服务,它可以生成“任何”类型的文件(可以是图像、文档、txt甚至pdf),也可以是XML。到目前为止,我得到了以下代码:Java RESTful生成二进制文件,java,rest,cxf,binaryfiles,Java,Rest,Cxf,Binaryfiles,我是使用CXF和Spring创建RESTful Web服务的新手 这就是我的问题:我想创建一个服务,它可以生成“任何”类型的文件(可以是图像、文档、txt甚至pdf),也可以是XML。到目前为止,我得到了以下代码: @Path("/download/") @GET @Produces({"application/*"}) public CustomXML getFile() throws Exception; 我不知道从哪里开始,所以请耐心等待 编辑: 陆炳泉的完整代码(谢谢!) 如果它将返
@Path("/download/")
@GET
@Produces({"application/*"})
public CustomXML getFile() throws Exception;
我不知道从哪里开始,所以请耐心等待
编辑:
陆炳泉的完整代码(谢谢!)
如果它将返回任何文件,您可能希望使您的方法更“通用”,并返回javax.ws.rs.core.Response,您可以通过编程方式设置内容类型头:
@Path("/download/")
@GET
public javax.ws.rs.core.Response getFile() throws Exception {
if (/* want the pdf file */) {
return Response.ok(new File(/*...*/)).type("application/pdf").build();
}
/* default to xml file */
return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build();
}
我们还使用CXF和Spring,这是我更喜欢的API
import javax.ws.rs.core.Context;
@Path("/")
public interface ContentService
{
@GET
@Path("/download/")
@Produces(MediaType.WILDCARD)
InputStream getFile() throws Exception;
}
@Component
public class ContentServiceImpl implements ContentService
{
@Context
private MessageContext context;
@Override
public InputStream getFile() throws Exception
{
File f;
String contentType;
if (/* want the pdf file */) {
f = new File("...pdf");
contentType = MediaType.APPLICATION_PDF_VALUE;
} else { /* default to xml file */
f = new File("custom.xml");
contentType = MediaType.APPLICATION_XML_VALUE;
}
context.getHttpServletResponse().setContentType(contentType);
context.getHttpServletResponse().setHeader("Content-Disposition", "attachment; filename=" + f.getName());
return new FileInputStream(f);
}
}
试着从解释你的问题开始。到目前为止,您只描述了您所做的工作,但没有提到代码运行时会发生什么,遇到了什么错误,等等。您是否试图让框架为
/download
下的每个请求调用getFile()
,以便它能够生成请求的文件?我想,在这种情况下,您要问的是getFile()
的实现如何能够找到实际请求的内容。@Wyzard是的,我希望不太需要实现和注释类型
import javax.ws.rs.core.Context;
@Path("/")
public interface ContentService
{
@GET
@Path("/download/")
@Produces(MediaType.WILDCARD)
InputStream getFile() throws Exception;
}
@Component
public class ContentServiceImpl implements ContentService
{
@Context
private MessageContext context;
@Override
public InputStream getFile() throws Exception
{
File f;
String contentType;
if (/* want the pdf file */) {
f = new File("...pdf");
contentType = MediaType.APPLICATION_PDF_VALUE;
} else { /* default to xml file */
f = new File("custom.xml");
contentType = MediaType.APPLICATION_XML_VALUE;
}
context.getHttpServletResponse().setContentType(contentType);
context.getHttpServletResponse().setHeader("Content-Disposition", "attachment; filename=" + f.getName());
return new FileInputStream(f);
}
}