【问题标题】:Reading InputStream from webservice response从 Web 服务响应中读取 InputStream
【发布时间】:2015-11-26 09:00:00
【问题描述】:

我正在尝试做的似乎是一件非常简单的事情,从 Jersey 网络服务获取 InputStream,该服务是从类 RestResponse 返回的。但我没有将流发送给我的客户:

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

任何想法,我错过了什么?是不是只能通过管道传输流?

【问题讨论】:

  • 除了返回它之外,您是否试图对流做任何事情?
  • 现在,我只是想将它通过管道传输到 System.out。我省略了那部分。但这在我指出的地方是成功的。

标签: java web-services stream inputstream


【解决方案1】:

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

更新:

看来您的实际问题是由在您有机会使用它之前关闭InputStream 引起的。因此解决方案是在您需要它之前保持流打开,然后再关闭它。

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

【讨论】:

  • 我检查过之前没有消费过这个流。我唯一一次通过管道传输到 System.out 是在最后,在客户端。但没有成功。我想,只有设置this.responseStream = responseBodyStream; 不会消耗流。
  • 等一下...System.out 是如何成功的,但如果在此之前尝试失败?
  • 好吧,如果我在 RestResponse 的构造函数中执行System.out,它会给我流内容。如果我在此之后执行System.out(例如在getResponseStream() 中,它会失败。
  • 这听起来像是正在关闭流。你能把调用构造函数的代码贴出来吗?
  • 是的,添加了更多代码。我明白你的意思了。当我刚刚从同一个流返回纯文本时,我像以前一样关闭了 InputStream。
猜你喜欢
  • 1970-01-01
  • 2017-09-07
  • 2015-07-18
  • 2021-06-15
  • 1970-01-01
  • 2020-04-23
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多