有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用于socket使用的java GZIPOutputStream长度

我正在用Java开发一个带有socket的小型Web服务器。我让它像HTTP一样工作,使用Connection: keep-alive,等等。 现在,我想压缩(GZIP)发送的数据

为了确保遵守Connection: keep-alive,我从不关闭socket。这就是为什么我需要在每个响应中发送content-length。使用普通文件很容易。 我就是这样做的

out.println(HTTP_VERSION + " 200 OK");
out.println("Content-Type: "+Files.probeContentType(f.toPath())+"; charset=UTF-8\nContent-Length:"+f.length()+"\n");
Files.copy(f.toPath(), so.getOutputStream());

但是我不知道如何检索我的GZIPOutputStream的大小

这就是我想做的

GZIPOutputStream gos = new GZIPOutputStream(so.getOutputStream());
out.println(HTTP_VERSION + " 200 OK");
out.println("Content-Type: "+Files.probeContentType(f.toPath())+"; charset=UTF-8\nContent-Encoding: gzip\nContent-Length:"+SIZE HERE+"\n");
Files.copy(f.toPath(), gos);
gos.finish();

有什么想法吗?非常感谢。圣诞快乐

更新

我设法解决了我的问题。这是最终代码:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(bos);
Files.copy(f.toPath(), gos);
gos.finish();
out.println("Content-Type: "+Files.probeContentType(f.toPath())+"; charset=UTF-8\nContent-Encoding: gzip\nContent-Length:"+bos.toByteArray().length+"\n");
bos.writeTo(so.getOutputStream());

谢谢你和布兰特·昂格


共 (1) 个答案

  1. # 1 楼答案

    我设法解决了我的问题。这是最终代码:

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(bos);
    Files.copy(f.toPath(), gos);
    gos.finish();
    out.println("Content-Type: "+Files.probeContentType(f.toPath())+"; charset=UTF-8\nContent-Encoding: gzip\nContent-Length:"+bos.toByteArray().length+"\n");
    bos.writeTo(so.getOutputStream());
    

    谢谢你和布兰特·昂格