如何基于Apache HttpComponents为服务器添加Keep-Alive头?

时间:2012-01-07 11:54:36

标签: java http apache-httpcomponents

如果连接只是持久性的话,我怎样才能使用Apache HttpComponents向响应添加“Connection:Keep-Alive”和“Keep-Alive:timeout = x,max = y”标题?

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

为什么我这样做:

标准行为是HttpComponents在持久连接的响应中不进行任何更改,并为非持久连接添加“Connection:close”。这在大多数情况下效果很好。

我希望有一个Keep-Alive标头,因为基于标准java.net.HttpURLConnection的客户端会在超时5秒后超时并丢弃连接,除非服务器上一次响应中存在Keep-Alive标头。我想使用Keep-Alive来定义超过5秒的超时。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

我没试过这个,但似乎你可以为你的httpCleint编写一个自定义的'ConnectionKeepAliveStrategy'。这是文档HttpComponents Custom stratagey

参见第2.11节