【问题标题】:Using Ion write(outputStream)使用离子写入(输出流)
【发布时间】:2013-08-01 21:55:11
【问题描述】:

我不明白在 Ion 中应该如何使用 write(outputStream) 方法。我的目标是获得一个可以直接输入 Jackson 的 InputStream,如下所示:

Response<OutputStream> response = Ion.with(context, "http://example.com/mydata.json").write(outputStream).withResponse().get();
MyModel m = jacksonJsonMapper.convertValue(inputStream, MyModel.class);

但我不知道从哪里获取输入和输出流,以及如何将它们相互连接。

【问题讨论】:

    标签: android networking androidasync-koush ion-koush


    【解决方案1】:

    好的,根据这个答案想出了一个解决方案:Most efficient way to create InputStream from OutputStream

    看起来我想使用 PipedOutputStream 和 PipedInputStream。因为我们现在阻止从 InputStream 读取,我不再想阻止 Ion 调用,所以我删除了 .get()。最终代码如下所示:

    PipedInputStream inputStream = new PipedInputStream();
    PipedOutputStream outputStream = new PipedOutputStream(inputStream);
    Ion.with(context, "http://example.com/mydata.json").write(outputStream).withResponse();
    MyModel m = jacksonJsonMapper.convertValue(inputStream, MyModel.class);
    

    【讨论】:

    • 您不需要 withResponse() 调用,这仅在您需要标头等时才有用。
    • 另外,我认为 jackson 调用会阻塞 inputStream,所以要小心它不是在 UI 线程上完成的。我会看看我是否可以添加一个 asStream() 方法,它会给你一个更简单的方法来做到这一点。
    • 是的,我确实想要标题,主要是为了检查状态码。是的,杰克逊的电话会在网络上阻塞,但这就是我要找的。我已经在后台线程中调用了这一切。 asStream() 方法可能很好,但与所有其他 as*() 方法不同,它必须阻塞,因此可能不一致。
    猜你喜欢
    • 1970-01-01
    • 2010-10-02
    • 2018-05-25
    • 2013-04-03
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2012-04-02
    • 2010-10-30
    相关资源
    最近更新 更多