2

我正在尝试将 InputStream 发布到 RESTful 服务。对于普通文件,这很好。

在另一个地方,我正在尝试将许多文件即时写入管道 zip 流。为此,我有一个扩展类,InputStreamread()被调用时,它将下一个文件写入管道。写入第一个文件后,我调用ZipOutputStream.closeEntry()但它挂起。为什么??

当我在单元测试中测试这个类时,它工作正常。当我尝试发布此对象时,它会挂起。调试器告诉我它正在等待锁定SocketWrapper

请注意,我还尝试将媒体类型设置为application/octet-stream. 此外,从不调用 RESTful 方法。

流类...

static class MultiStreamZipInputStream extends InputStream {

    private final Iterator<InputStream> streams;
    private final byte[] buffer = new byte[4096];
    private InputStream inputStream;
    private ZipOutputStream zipOutputStream;
    private InputStream currentStream;
    private int counter = 0;

    public MultiStreamZipInputStream(List<InputStream> streamList) {

        streams = streamList.iterator();
        currentStream = streams.next();

        try {
            PipedOutputStream out = new PipedOutputStream();
            inputStream = new PipedInputStream(out);

            zipOutputStream = new ZipOutputStream(out);
            ZipEntry entry = new ZipEntry(String.valueOf(counter++)); // Use counter for random name
            zipOutputStream.putNextEntry(entry);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public int read()
        throws IOException {

        if (inputStream.available() != 0)
            return inputStream.read();

        if (currentStream == null)
            return -1;

        int bytesRead = currentStream.read(buffer);
        if (bytesRead >= 0) {

            zipOutputStream.write(buffer,  0,  bytesRead);
            zipOutputStream.flush();

        } else  {

            currentStream.close();
            zipOutputStream.closeEntry();

            if (!streams.hasNext()) {
                currentStream = null;
                return -1;
            }

            currentStream = streams.next();
            zipOutputStream.putNextEntry(new ZipEntry(String.valueOf(counter++)));
        }

        return read();
    }
}

发帖代码...

        MultiStreamZipInputStream myStream = ...

        Client client = Client.create();
        Builder webResource = client.resource("some URL").type("application/x-zip-compressed");
        webResource.post(ClientResponse.class, myStream);

另一端的 REST 方法...

@POST
@Path("/somemethod")
@Produces(MediaType.APPLICATION_JSON)
@Consumes({"application/x-zip-compressed"})
public Response someMethod(InputStream data) {...
4

0 回答 0