2012-01-07 2 views
1

어떻게 아파치 HttpComponents를 사용하여 응답에 "Connection : Keep-Alive"및 "Keep-Alive : timeout = x, max = y"헤더를 추가 할 수 있습니까?Apache HttpComponents 기반 서버에 Keep-Alive 헤더를 추가하는 방법은 무엇입니까?

HttpComponents가이 연결이 지속되지 않는다고 판단하면 응답을 보낸 후 "Connection : close"헤더를 추가합니다. 이 경우에는 Keep-Alive 헤더가 필요 없습니다. 나는이 일을 해요 왜

: 비 영구적 인 연결 : HttpComponents는 영구 연결에 대한 응답에서 아무 것도 변경하지 않고, "가까운 연결"을 추가 할 수

표준 행동입니다. 이것은 대부분의 경우에 잘 작동합니다.

표준 java.net.HttpURLConnection을 기반으로하는 클라이언트가 5 초 동안 사용하지 않으면 연결이 끊어 지거나 연결이 끊어지기 때문에 Keep-Alive 헤더가 필요합니다. 섬기는 사람. Keep-Alive를 사용하여 5 초보다 긴 시간 제한을 정의하고 싶습니다.

+0

가능한 중복 [요청 헤더를 설정, 추가하는 방법을 HttpClient?] (http://stackoverflow.com/questions/13743205/how-to-add-set-and-get-header-in-request-of-httpclient) –

+0

이것은 http : //와 중복되지 않습니다. stackoverflow.com/questions/13743205/how-to-add-se HttpClient가 아니라 서버 측에 대해 묻고 있습니다 (11 개월 전 게시했습니다). –

답변

1

당신은 추가 "- 살아 계속 연결"HttpResponseInterceptor을 추가 할 수 있습니다 문서 HttpComponents Custom stratagey

참조 섹션입니다 필요한 경우 "Connection : close"헤더를 설정 한 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(); 
0

나는 이것을 시도하지 않았지만 httpCleint에 대한 사용자 지정 'ConnectionKeepAliveStrategy'를 코딩 할 수 있습니다. 와 "연결 유지 : 시간 초과 =의 X를, 최대는 = Y"는 응답 헤더가에 따라 : 다음은 2.11

+0

네가 말한대로 말하자면, 누가 서버와 클라이언트를 직접 작성하고 있으며 클라이언트 측에서 HttpClient를 사용할 수 있습니다. 하지만이 경우 모든 클라이언트를 제어하지 않기 때문에 서버에서 Keep-Alive 헤더를 보내야합니다. –