NanoHttpd - 返回gzipped响应

问题描述 投票:0回答:1

如何在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?

java webserver gzip nanohttpd
1个回答
0
投票

将这样的内容添加到您的服务器:

protected boolean useGzipWhenAccepted(Response r) {
    return true;
}

此外,没有必要使用res.setGzipEncoding(true);,因为它是自动调用。

© www.soinside.com 2019 - 2024. All rights reserved.