从 web 服务响应中读取 InputStream

Reading InputStream from webservice response

我想做的事情似乎很简单,从 class RestResponse 返回的 Jersey Web 服务获取 InputStream。但是我没有将流传输到我的客户端:

public class RestResponse {
    private InputStream responseStream;

    public RestResponse(InputStream responseBodyStream) throws IOException{     
        this.responseStream = responseBodyStream;   
        //here I can get the stream contents from this.responseStream
    }

    public InputStream getResponseStream() throws IOException { 
        //here stream content is empty, if called from outside
        //only contains content, if called from constructor
        return this.responseStream;
    }
}

public class HttpURLConnectionClient{

    public RestResponse call(){
        try{
            ....

            InputStream in = httpURLConnection.getInputStream();
            RestResponse rr = new RestResponse(in); 
        }finally{
           in.close(); <- this should be the suspect
        }
    }
}


    RestResponse rr = httpURLConnectionClient.call()//call to some url
    rr.getResponseStream(); //-> stream content is empty

任何想法,我缺少什么?不可能只通过管道传输流吗?

某些类型的 InputStream 只能在 Java 中读取一次。根据您上面的评论,当您将 System.out 传送到 System.out 时,您似乎正在使用 InputStream。尝试注释掉对 System.out 的调用,看看您是否可以访问您的 InputStream。还要确保在您需要它之前,流不会在代码中的其他任何地方被消耗。

更新:

看来您的实际问题是在您有机会使用 InputStream 之前关闭它造成的。所以解决方案是保持流打开直到你需要它,然后关闭它。

通常情况下,打开一个流并长时间保持打开状态并不是一个好的设计实践,因为这样底层资源将无法供其他任何需要它的人使用。所以你应该打开流,只有在你真正需要它的时候才使用它。