【问题标题】:How to add Keep-Alive header for server based on Apache HttpComponents?如何为基于 Apache HttpComponents 的服务器添加 Keep-Alive 标头?
【发布时间】:2012-02-04 20:52:46
【问题描述】:

如果连接将是持久的,如何使用 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 秒的超时时间。

【问题讨论】:

标签: java http apache-httpcomponents


【解决方案1】:

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

请参阅第 2.11 节

【讨论】:

  • 是的,照你说的做是对于那些自己编写服务器和客户端并且可以在客户端使用HttpClient的人的解决方案。但在这种情况下,我需要我的服务器发送一个 Keep-Alive 标头,因为我不控制所有客户端。
【解决方案2】:

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

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();

【讨论】:

    猜你喜欢
    • 2013-02-24
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    相关资源
    最近更新 更多