如何在NanoHttpd中启用GZIP压缩?
Java代码(启动Web服务器并为任何请求返回相同的默认响应):
package com.example;
import java.io.*;
import java.nio.charset.Charset;
import fi.iki.elonen.NanoHTTPD;
import static fi.iki.elonen.NanoHTTPD.Response.Status.OK;
public class App extends NanoHTTPD {
public App() throws IOException {
super(8080);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
public static void main(String[] args) {
try {
new App();
} catch (IOException ioe) {
System.err.println("Couldn't start server:\n" + ioe);
}
}
@Override
public Response serve(IHTTPSession session) {
ByteArrayInputStream resBody = new ByteArrayInputStream(new byte[0]);
try {
resBody = new ByteArrayInputStream("{\"response\":1}".getBytes("UTF-8"));
} catch (UnsupportedEncodingException ex) {
}
Response res = newChunkedResponse(OK, "application/json", resBody);
res.setGzipEncoding(true);
return res;
}
}
这个请求:
GET / HTTP/1.1
Host: localhost:8080
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,ru;q=0.8
产生此响应:
HTTP/1.1 200 OK
Content-Type: application/json
Date: Tue, 28 Aug 2018 11:39:12 GMT
Connection: keep-alive
Transfer-Encoding: chunked
{"response":1}
是否可以为NanoHttpd响应启用GZIP?
答案 0 :(得分:0)
将类似这样的内容添加到您的服务器中:
protected boolean useGzipWhenAccepted(Response r) {
return true;
}
也无需使用res.setGzipEncoding(true);
,因为它会自动被调用。
答案 1 :(得分:0)
如果标头不包含{'Accept-Encoding':'gzip'}甚至不包含'Accept-Encoding'标头,则NanoHTTPD将默认将useGzipEncode设置为false。要解决此问题,您可以在外部对数据进行gzip并将byte []传递给响应。
public class Server extends NanoHTTPD {
byte[] bArr;
public Server(int port) {
super(port);
}
@Override
public Response serve(IHTTPSession session) {
return newFixedLengthResponse(Response.Status.OK,"application/octect-stream",new ByteArrayInputStream(this.bArr),bArr.length);
}
public void compressWithGzip(byte[] bArr) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
try {
GZIPOutputStream gzip = new GZIPOutputStream(bout);
gzip.write(bArr,0,bArr.length);
gzip.close();
setByteArray(bout.toByteArray());
bout.close();
} catch (IOException e) {
//TODO
}
}
public void setByteArray(byte[] byteArray) {
this.bArr = byteArray;
}
}