Gog*_*l31 3 java http gzipoutputstream
我试图通过 java 套接字发送压缩的 HTML 文件,但浏览器显示一个空的 HTML 文件。
问题是,当我尝试发送未压缩的 HTML 时,发现一切正常(是的,我确实相应地修改了 HTTP 标头)。
private void sendResponse(String headers, String body) throws IOException
{
BufferedOutputStream output = new BufferedOutputStream(
this.SOCKET.getOutputStream());
byte[] byteBody = null;
// GZIP compression
if(body != null && this.encoding.contains("gzip"))
{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
GZIPOutputStream zipStream = new GZIPOutputStream(byteStream);
zipStream.write(body.getBytes(this.charset));
zipStream.flush();
byteBody = byteStream.toByteArray();
byteStream.flush();
byteStream.close();
zipStream.close();
}
else
byteBody = body.getBytes(this.charset);
// Sending response
byte[] msg1 = (Integer.toHexString(byteBody.length) + "\r\n")
.getBytes(this.charset);
byte[] msg2 = byteBody;
byte[] msg3 = ("\r\n" + "0").getBytes(this.charset);
output.write(headers.getBytes(this.charset));
output.write(msg1);
output.write(msg2);
output.write(msg3);
output.flush();
output.close();
}
Run Code Online (Sandbox Code Playgroud)
基本上,headers包含 HTTP 标头,body 包含HTML 文件。其余的似乎是不言自明的。什么会导致这种行为?
编辑:标头是这样生成的:
headers = "HTTP/1.1 200 OK\r\n";
headers += "Date: " + WebServer.getServerTime(Calendar.getInstance()) + "\r\n";
headers += "Content-Type: text/html; charset=" + this.charset + "\r\n";
headers += "Set-Cookie: sessionID=" + newCookie + "; Max-Age=600\r\n";
headers += "Connection: close \r\n";
if(this.encoding.contains("gzip"))
headers += "Content-Encoding: gzip\r\n";
headers += "Transfer-Encoding: chunked \r\n";
headers += "\r\n";
Run Code Online (Sandbox Code Playgroud)
问题是 a在调用GZIPOutputStream
该方法之前并不完整。finish()
close()
当您进行流传输时会自动调用它。
byteStream.toByteArray()
由于您在此之前致电,因此您无法获得完整的数据。
此外,您不需要调用flush()
,因为当您调用 时,这也会自动完成close()
。关闭会GZIPOutputStream
自动关闭底层流(即 )ByteArrayOutputStream
。
所以,你的代码应该是:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
GZIPOutputStream zipStream = new GZIPOutputStream(byteStream);
zipStream.write(body.getBytes(this.charset));
zipStream.close();
byteBody = byteStream.toByteArray();
Run Code Online (Sandbox Code Playgroud)