我在Scala中使用Play的WS API来发出HTTP请求。我需要发送一个gzip post请求,我很难做到这一点。
val compressedData = deflate(data).get
val request = (<requestHolder>).withHeaders("Content-Encoding" -> "gzip")
.withHeaders("Content-Length" -> compressedData.size.toString).withHeaders("Content-Type" -> "application/json")
val temp = getStringFromByteArray(compressedData)
request.post(temp).map { r =>
if(r.status / 100 == 2) {
r.json
}
else { ...} }
这是我的gzip助手方法:
def deflate(txt: String): Try[ByteArrayOutputStream] = Try {
val outputStream = new ByteArrayOutputStream()
val zipStream = new GZIPOutputStream(outputStream)
zipStream.write(txt.getBytes)
zipStream.close()
outputStream
}
def getStringFromByteArray(stream: ByteArrayOutputStream): String = {
Base64.encodeBase64String(stream.toByteArray)
}