我只有几个文件(javascript和CSS),我想要GZIP,我的设置很简单,我通过读取本地文件获得输入流:
new FileInputStream(path)
然后我将输入流解析为GZIP并返回一个写入输出流的字节数组。
在浏览器上,我收到了一个带有前置奇怪字符的回复,我不确定为什么会发生这种情况,有什么想法吗?
import java.io._
import java.util.zip.{GZIPInputStream, GZIPOutputStream}
object GzipCompression {
def serialise(inputStream: InputStream): Array[Byte] = {
val stream: ByteArrayOutputStream = new ByteArrayOutputStream()
val gzipOut = new GZIPOutputStream(stream)
val oos = new ObjectOutputStream(gzipOut)
val buffer = new Array[Byte](1024)
var len = inputStream.read(buffer)
while ( {
len != -1
}) {
oos.write(buffer, 0, len)
len = inputStream.read(buffer)
}
oos.flush()
oos.close()
stream.toByteArray
}
}
// my implementation
val outputStream = request.servletResponse.getOutputStream
val inputStream = new FileInputStream("script.js")
val byteArray = GzipCompression.serialise(inputStream)
servletResponse.setHeader("Content-Type", "text/javascript")
servletResponse.setHeader("Content-Encoding", "gzip")
servletResponse.setHeader("Vary", "Accept-Encoding")
outputStream.write(byteArray)
outputStream.close()
PS:
此外,如果我使用new GZIPInputStream()
解码byteArray,我会在开始时将正确的输出作为字符串返回而没有任何奇怪的字符,所以它看起来像Jetty ServletOutputStream
导致此