1

仅当连接将是持久的时,如何使用 Apache HttpComponents 将“Connection: Keep-Alive”和“Keep-Alive: timeout=x, max=y”标头添加到响应中?

如果 HttpComponents 决定这个连接不会是持久的,它会在我给出响应后添加一个“连接:关闭”标题。在这种情况下,我不想要 Keep-Alive 标头。

为什么我这样做:

标准行为是 HttpComponents 不更改持久连接的响应中的任何内容,并为非持久连接添加“连接:关闭”。这在大多数情况下都很有效。

我想要一个 Keep-Alive 标头,因为基于标准 java.net.HttpURLConnection 的客户端将在 5 秒不活动后超时并丢弃连接,除非服务器的先前响应中有 Keep-Alive 标头。我想使用 Keep-Alive 来定义超过 5 秒的超时。

4

2 回答 2

1

您可以添加 HttpResponseInterceptor,它将“Connection: Keep-Alive”和“Keep-Alive: timeout=x, max=y”标头添加到响应中,具体取决于来自 org.apache.http.protocol.ResponseConnControl 的评估,它设置了“连接:关闭”标题,在需要时。

class ResposeKeepAliveHeaderMod implements HttpResponseInterceptor {

    @Override
    public void process(HttpResponse response, HttpContext context)
            throws HttpException, IOException {
        final Header explicit = response.getFirstHeader(HTTP.CONN_DIRECTIVE);
        if (explicit != null && HTTP.CONN_CLOSE.equalsIgnoreCase(explicit.getValue())) {
            // Connection persistence explicitly disabled
            return;
        }else{
            // "Connection: Keep-Alive" and "Keep-Alive: timeout=x, max=y" 
            response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
            response.setHeader(HTTP.CONN_KEEP_ALIVE, "timeout=30, max=100");
        }

    }      
   }

您需要在 ResponseConnControl 之后将其添加到 HttpProcessor:

HttpProcessor httpProcessor = HttpProcessorBuilder.create()
            //.addFirst(new RequestTrace())
            .add(new ResponseDate())
            //.add(new ResponseServer("MyServer-HTTP/1.1"))
            .add(new ResponseContent())
            .add(new ResponseConnControl())
            .addLast(new ResposeKeepAliveHeaderMod())
            .build();

然后构建服务器:

final HttpServer server = ServerBootstrap.bootstrap()
            .setListenerPort(9090)
            .setHttpProcessor(httpProcessor)
            .setSocketConfig(socketConfig)
            .setExceptionLogger(new StdErrorExceptionLogger ())
            .setHandlerMapper(handle_map)
            .create();
于 2016-03-28T15:18:22.630 回答
0

我还没有尝试过,但您似乎可以为您的 httpCleint 编写自定义的“ConnectionKeepAliveStrategy”。这是文档HttpComponents 自定义策略

请参阅第 2.11 节

于 2012-01-07T13:14:14.277 回答