如何使用JAX-RS流式传输无尽的InputStream [英] How to stream an endless InputStream with JAX-RS

查看:127
本文介绍了如何使用JAX-RS流式传输无尽的InputStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个无限的InputStream,其中包含一些数据,我想返回这些数据以响应GET HTTP请求.我希望我的Web/API客户端可以无休止地阅读它.如何使用JAX-RS?我正在尝试:

I have an endless InputStream with some data, which I want to return in response to a GET HTTP request. I want my web/API client to read from it endlessly. How can I do it with JAX-RS? I'm trying this:

@GET
@Path("/stream")
@Produces(MediaType.TEXT_PLAIN)
public StreamingOutput stream() {
    final InputStream input = // get it
    return new StreamingOutput() {
        @Override
        public void write(OutputStream out) throws IOException {
            while (true) {
                out.write(input.read());
                out.flush();
            }
        }
    };
}

但是客户端没有显示内容.但是,如果我添加OutputStream#close(),则服务器将在此时发送内容.我如何才能使其真正流式传输?

But content doesn't appear for the client. However, if I add OutputStream#close(), the server delivers the content at that very moment. How can I make it truly streamable?

推荐答案

因此,您遇到了刷新问题,可以尝试按照规范中的说明获取ServletResponse:

So, you have flush issues, you could try to get the ServletResponse as the spec says:

@Context批注可用于指示对 Servlet定义的资源.基于Servlet的实现必须支持 注入以下Servlet定义的类型:ServletConfig, ServletContext,HttpServletRequest和HttpServletResponse.

The @Context annotation can be used to indicate a dependency on a Servlet-defined resource. A Servlet- based implementation MUST support injection of the following Servlet-defined types: ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse.

注入的HttpServletResponse允许资源方法提交 返回之前的HTTP响应.一个实现必须检查 提交状态,并且仅在响应为 尚未提交.

An injected HttpServletResponse allows a resource method to commit the HTTP response prior to returning. An implementation MUST check the committed status and only process the return value if the response is not yet committed.

然后刷新所有内容,如下所示:

Then flushing everything you can, like this:

@Context
private HttpServletResponse context;

@GET
@Path("/stream")
@Produces(MediaType.TEXT_PLAIN)
public String stream() {
    final InputStream input = // get it
    ServletOutputStream out = context.getOutputStream();
            while (true) {
                out.write(input.read());
                out.flush();
                context.flushBuffer();
            }
    return "";
}

这篇关于如何使用JAX-RS流式传输无尽的InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆