我正在用Java开发一个带套接字的小型with服务器。我让它像HTTP一样工作,使用Connection: keep-alive,等等。现在,我想压缩(GZIP)发送的数据。
为了确保Connection: keep-alive被尊重,我从不关闭套接字。这就是为什么我需要在每个响应中发送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());感谢JB Nizet和Brant Unger
发布于 2015-04-11 20:45:38
我设法解决了我的问题。这是最终的代码:
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());感谢JB Nizet和Brant Unger
https://stackoverflow.com/questions/20764957
复制相似问题