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 package org.apache.hc.client5.http.impl;
28
29 import java.util.Iterator;
30
31 import org.apache.hc.client5.http.ConnectionKeepAliveStrategy;
32 import org.apache.hc.client5.http.config.RequestConfig;
33 import org.apache.hc.client5.http.protocol.HttpClientContext;
34 import org.apache.hc.core5.annotation.Contract;
35 import org.apache.hc.core5.annotation.ThreadingBehavior;
36 import org.apache.hc.core5.http.HeaderElement;
37 import org.apache.hc.core5.http.HeaderElements;
38 import org.apache.hc.core5.http.HttpResponse;
39 import org.apache.hc.core5.http.message.MessageSupport;
40 import org.apache.hc.core5.http.protocol.HttpContext;
41 import org.apache.hc.core5.util.Args;
42 import org.apache.hc.core5.util.TimeValue;
43
44
45
46
47
48
49
50
51
52
53
54 @Contract(threading = ThreadingBehavior.STATELESS)
55 public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
56
57 public static final DefaultConnectionKeepAliveStrategy INSTANCE = new DefaultConnectionKeepAliveStrategy();
58
59 @Override
60 public TimeValue getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
61 Args.notNull(response, "HTTP response");
62 final Iterator<HeaderElement> it = MessageSupport.iterate(response, HeaderElements.KEEP_ALIVE);
63 while (it.hasNext()) {
64 final HeaderElement he = it.next();
65 final String param = he.getName();
66 final String value = he.getValue();
67 if (value != null && param.equalsIgnoreCase("timeout")) {
68 try {
69 return TimeValue.ofSeconds(Long.parseLong(value));
70 } catch(final NumberFormatException ignore) {
71 }
72 }
73 }
74 final HttpClientContext clientContext = HttpClientContext.cast(context);
75 final RequestConfig requestConfig = clientContext.getRequestConfigOrDefault();
76 return requestConfig.getConnectionKeepAlive();
77 }
78
79 }