如何在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?
发布于 2018-08-30 16:17:09
将类似以下内容添加到您的服务器:
protected boolean useGzipWhenAccepted(Response r) {
return true;
}也不需要使用res.setGzipEncoding(true);,因为它是自动调用的。
发布于 2020-08-31 16:45:43
如果报头不包含{ 'Accept-Encoding‘:' gzip '}或者甚至不包含’Accept-Encoding‘报头,那么NanoHTTPD会默认设置useGzipEncode,因为false.To克服了这一点,你可以在外部对数据进行压缩,并将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;
}
}https://stackoverflow.com/questions/52057404
复制相似问题