View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http.impl;
29  
30  import java.util.Iterator;
31  
32  import org.apache.hc.core5.annotation.Contract;
33  import org.apache.hc.core5.annotation.ThreadingBehavior;
34  import org.apache.hc.core5.http.ConnectionReuseStrategy;
35  import org.apache.hc.core5.http.Header;
36  import org.apache.hc.core5.http.HeaderElements;
37  import org.apache.hc.core5.http.HttpHeaders;
38  import org.apache.hc.core5.http.HttpRequest;
39  import org.apache.hc.core5.http.HttpResponse;
40  import org.apache.hc.core5.http.HttpVersion;
41  import org.apache.hc.core5.http.ProtocolVersion;
42  import org.apache.hc.core5.http.message.BasicTokenIterator;
43  import org.apache.hc.core5.http.message.MessageSupport;
44  import org.apache.hc.core5.http.protocol.HttpContext;
45  import org.apache.hc.core5.util.Args;
46  
47  /**
48   * Default implementation of a strategy deciding about connection re-use. The strategy
49   * determines whether a connection is persistent or not based on the message’s protocol
50   * version and {@code Connection} header field if present. Connections will not be
51   * re-used and will close if any of these conditions is met
52   * <ul>
53   *     <li>the {@code close} connection option is present in the request message</li>
54   *     <li>the response message content body is incorrectly or ambiguously delineated</li>
55   *     <li>the {@code close} connection option is present in the response message</li>
56   *     <li>If the received protocol is {@code HTTP/1.0} (or earlier) and {@code keep-alive}
57   *     connection option is not present</li>
58   * </ul>
59   * In the absence of a {@code Connection} header field, the non-standard but commonly used
60   * {@code Proxy-Connection} header field will be used instead. If no connection options are
61   * explicitly given the default policy for the HTTP version is applied. {@code HTTP/1.1}
62   * (or later) connections are re-used by default. {@code HTTP/1.0} (or earlier) connections
63   * are not re-used by default.
64   *
65   * @since 4.0
66   */
67  @Contract(threading = ThreadingBehavior.IMMUTABLE)
68  public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy {
69  
70      public static final DefaultConnectionReuseStrategy INSTANCE = new DefaultConnectionReuseStrategy();
71  
72      public DefaultConnectionReuseStrategy() {
73          super();
74      }
75  
76      // see interface ConnectionReuseStrategy
77      @Override
78      public boolean keepAlive(
79              final HttpRequest request, final HttpResponse response, final HttpContext context) {
80          Args.notNull(response, "HTTP response");
81  
82          if (request != null) {
83              final Iterator<String> ti = new BasicTokenIterator(request.headerIterator(HttpHeaders.CONNECTION));
84              while (ti.hasNext()) {
85                  final String token = ti.next();
86                  if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
87                      return false;
88                  }
89              }
90          }
91  
92          // Check for a self-terminating entity. If the end of the entity will
93          // be indicated by closing the connection, there is no keep-alive.
94          final Header teh = response.getFirstHeader(HttpHeaders.TRANSFER_ENCODING);
95          if (teh != null) {
96              if (!HeaderElements.CHUNKED_ENCODING.equalsIgnoreCase(teh.getValue())) {
97                  return false;
98              }
99          } else {
100             final String method = request != null ? request.getMethod() : null;
101             if (MessageSupport.canResponseHaveBody(method, response)
102                     && response.containsHeaders(HttpHeaders.CONTENT_LENGTH) != 1) {
103                 return false;
104             }
105         }
106 
107         // Check for the "Connection" header. If that is absent, check for
108         // the "Proxy-Connection" header. The latter is an unspecified and
109         // broken but unfortunately common extension of HTTP.
110         Iterator<Header> headerIterator = response.headerIterator(HttpHeaders.CONNECTION);
111         if (!headerIterator.hasNext()) {
112             headerIterator = response.headerIterator("Proxy-Connection");
113         }
114 
115         final ProtocolVersion ver = context.getProtocolVersion();
116         if (headerIterator.hasNext()) {
117             if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
118                 final Iterator<String> it = new BasicTokenIterator(headerIterator);
119                 while (it.hasNext()) {
120                     final String token = it.next();
121                     if (HeaderElements.CLOSE.equalsIgnoreCase(token)) {
122                         return false;
123                     }
124                 }
125                 return true;
126             }
127             final Iterator<String> it = new BasicTokenIterator(headerIterator);
128             while (it.hasNext()) {
129                 final String token = it.next();
130                 if (HeaderElements.KEEP_ALIVE.equalsIgnoreCase(token)) {
131                     return true;
132                 }
133             }
134             return false;
135         }
136         return ver.greaterEquals(HttpVersion.HTTP_1_1);
137     }
138 
139 }