1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.client5.http.protocol;
29
30 import java.io.IOException;
31
32 import org.apache.hc.client5.http.RouteInfo;
33 import org.apache.hc.core5.annotation.Contract;
34 import org.apache.hc.core5.annotation.ThreadingBehavior;
35 import org.apache.hc.core5.http.EntityDetails;
36 import org.apache.hc.core5.http.HeaderElements;
37 import org.apache.hc.core5.http.HttpException;
38 import org.apache.hc.core5.http.HttpHeaders;
39 import org.apache.hc.core5.http.HttpRequest;
40 import org.apache.hc.core5.http.HttpRequestInterceptor;
41 import org.apache.hc.core5.http.Method;
42 import org.apache.hc.core5.http.protocol.HttpContext;
43 import org.apache.hc.core5.util.Args;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47
48
49
50
51
52
53
54 @Contract(threading = ThreadingBehavior.STATELESS)
55 public class RequestClientConnControl implements HttpRequestInterceptor {
56
57 private static final Logger LOG = LoggerFactory.getLogger(RequestClientConnControl.class);
58
59 public RequestClientConnControl() {
60 super();
61 }
62
63 @Override
64 public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context)
65 throws HttpException, IOException {
66 Args.notNull(request, "HTTP request");
67
68 final String method = request.getMethod();
69 if (Method.CONNECT.isSame(method)) {
70 return;
71 }
72
73 final HttpClientContext clientContext = HttpClientContext.adapt(context);
74 final String exchangeId = clientContext.getExchangeId();
75
76
77 final RouteInfo route = clientContext.getHttpRoute();
78 if (route == null) {
79 if (LOG.isDebugEnabled()) {
80 LOG.debug("{} Connection route not set in the context", exchangeId);
81 }
82 return;
83 }
84
85 if (route.getHopCount() == 1 || route.isTunnelled()) {
86 if (!request.containsHeader(HttpHeaders.CONNECTION)) {
87 request.addHeader(HttpHeaders.CONNECTION, HeaderElements.KEEP_ALIVE);
88 }
89 }
90 }
91
92 }