您可以添加 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();