Java NanoHttpd-返回gzip响应
如何在中启用GZIP压缩 Java代码(启动web服务器并对任何请求返回相同的默认响应): 这项请求:Java NanoHttpd-返回gzip响应,java,webserver,gzip,nanohttpd,Java,Webserver,Gzip,Nanohttpd,如何在中启用GZIP压缩 Java代码(启动web服务器并对任何请求返回相同的默认响应): 这项请求: 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)
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?在服务器上添加类似的内容:
protected boolean useGzipWhenAccepted(Response r) {
return true;
}
也不需要使用
res.setgzipencode(true)代码>自动调用。如果标头不包含{'Accept-Encoding':'gzip'}或甚至不包含'Accept-Encoding'标头,那么NanoHTTPD将默认将useGzipEncode设置为false。要克服这一问题,您可以从外部gzip数据,并将字节[]传递给响应
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;
}
}
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;
}
}