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
58
59
60 public static final DefaultConnectionKeepAliveStrategy INSTANCE = new DefaultConnectionKeepAliveStrategy();
61
62 @Override
63 public TimeValue getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
64 Args.notNull(response, "HTTP response");
65 final Iterator<HeaderElement> it = MessageSupport.iterate(response, HeaderElements.KEEP_ALIVE);
66 while (it.hasNext()) {
67 final HeaderElement he = it.next();
68 final String param = he.getName();
69 final String value = he.getValue();
70 if (value != null && param.equalsIgnoreCase("timeout")) {
71 try {
72 return TimeValue.ofSeconds(Long.parseLong(value));
73 } catch(final NumberFormatException ignore) {
74 }
75 }
76 }
77 final HttpClientContext clientContext = HttpClientContext.cast(context);
78 final RequestConfig requestConfig = clientContext.getRequestConfigOrDefault();
79 return requestConfig.getConnectionKeepAlive();
80 }
81
82 }