Home | History | Annotate | Download | only in impl
      1 /*
      2  * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/module-main/src/main/java/org/apache/http/impl/DefaultConnectionReuseStrategy.java $
      3  * $Revision: 602537 $
      4  * $Date: 2007-12-08 11:42:06 -0800 (Sat, 08 Dec 2007) $
      5  *
      6  * ====================================================================
      7  * Licensed to the Apache Software Foundation (ASF) under one
      8  * or more contributor license agreements.  See the NOTICE file
      9  * distributed with this work for additional information
     10  * regarding copyright ownership.  The ASF licenses this file
     11  * to you under the Apache License, Version 2.0 (the
     12  * "License"); you may not use this file except in compliance
     13  * with the License.  You may obtain a copy of the License at
     14  *
     15  *   http://www.apache.org/licenses/LICENSE-2.0
     16  *
     17  * Unless required by applicable law or agreed to in writing,
     18  * software distributed under the License is distributed on an
     19  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     20  * KIND, either express or implied.  See the License for the
     21  * specific language governing permissions and limitations
     22  * under the License.
     23  * ====================================================================
     24  *
     25  * This software consists of voluntary contributions made by many
     26  * individuals on behalf of the Apache Software Foundation.  For more
     27  * information on the Apache Software Foundation, please see
     28  * <http://www.apache.org/>.
     29  *
     30  */
     31 
     32 package org.apache.http.impl;
     33 
     34 import org.apache.http.ConnectionReuseStrategy;
     35 import org.apache.http.HttpConnection;
     36 import org.apache.http.HeaderIterator;
     37 import org.apache.http.HttpEntity;
     38 import org.apache.http.HttpResponse;
     39 import org.apache.http.HttpVersion;
     40 import org.apache.http.ParseException;
     41 import org.apache.http.ProtocolVersion;
     42 import org.apache.http.protocol.HTTP;
     43 import org.apache.http.protocol.HttpContext;
     44 import org.apache.http.protocol.ExecutionContext;
     45 import org.apache.http.TokenIterator;
     46 import org.apache.http.message.BasicTokenIterator;
     47 
     48 /**
     49  * Default implementation of a strategy deciding about connection re-use.
     50  * The default implementation first checks some basics, for example
     51  * whether the connection is still open or whether the end of the
     52  * request entity can be determined without closing the connection.
     53  * If these checks pass, the tokens in the "Connection" header will
     54  * be examined. In the absence of a "Connection" header, the
     55  * non-standard but commonly used "Proxy-Connection" header takes
     56  * it's role. A token "close" indicates that the connection cannot
     57  * be reused. If there is no such token, a token "keep-alive" indicates
     58  * that the connection should be re-used. If neither token is found,
     59  * or if there are no "Connection" headers, the default policy for
     60  * the HTTP version is applied. Since HTTP/1.1, connections are re-used
     61  * by default. Up until HTTP/1.0, connections are not re-used by default.
     62  *
     63  * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
     64  * @author <a href="mailto:rolandw at apache.org">Roland Weber</a>
     65  *
     66  * @version $Revision: 602537 $
     67  *
     68  * @since 4.0
     69  *
     70  * @deprecated Please use {@link java.net.URL#openConnection} instead.
     71  *     Please visit <a href="http://android-developers.blogspot.com/2011/09/androids-http-clients.html">this webpage</a>
     72  *     for further details.
     73  */
     74 @Deprecated
     75 public class DefaultConnectionReuseStrategy
     76     implements ConnectionReuseStrategy {
     77 
     78     public DefaultConnectionReuseStrategy() {
     79         super();
     80     }
     81 
     82     // see interface ConnectionReuseStrategy
     83     public boolean keepAlive(final HttpResponse response,
     84                              final HttpContext context) {
     85         if (response == null) {
     86             throw new IllegalArgumentException
     87                 ("HTTP response may not be null.");
     88         }
     89         if (context == null) {
     90             throw new IllegalArgumentException
     91                 ("HTTP context may not be null.");
     92         }
     93 
     94         HttpConnection conn = (HttpConnection)
     95             context.getAttribute(ExecutionContext.HTTP_CONNECTION);
     96 
     97         if (conn != null && !conn.isOpen())
     98             return false;
     99         // do NOT check for stale connection, that is an expensive operation
    100 
    101         // Check for a self-terminating entity. If the end of the entity will
    102         // be indicated by closing the connection, there is no keep-alive.
    103         HttpEntity entity = response.getEntity();
    104         ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
    105         if (entity != null) {
    106             if (entity.getContentLength() < 0) {
    107                 if (!entity.isChunked() ||
    108                     ver.lessEquals(HttpVersion.HTTP_1_0)) {
    109                     // if the content length is not known and is not chunk
    110                     // encoded, the connection cannot be reused
    111                     return false;
    112                 }
    113             }
    114         }
    115 
    116         // Check for the "Connection" header. If that is absent, check for
    117         // the "Proxy-Connection" header. The latter is an unspecified and
    118         // broken but unfortunately common extension of HTTP.
    119         HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE);
    120         if (!hit.hasNext())
    121             hit = response.headerIterator("Proxy-Connection");
    122 
    123         // Experimental usage of the "Connection" header in HTTP/1.0 is
    124         // documented in RFC 2068, section 19.7.1. A token "keep-alive" is
    125         // used to indicate that the connection should be persistent.
    126         // Note that the final specification of HTTP/1.1 in RFC 2616 does not
    127         // include this information. Neither is the "Connection" header
    128         // mentioned in RFC 1945, which informally describes HTTP/1.0.
    129         //
    130         // RFC 2616 specifies "close" as the only connection token with a
    131         // specific meaning: it disables persistent connections.
    132         //
    133         // The "Proxy-Connection" header is not formally specified anywhere,
    134         // but is commonly used to carry one token, "close" or "keep-alive".
    135         // The "Connection" header, on the other hand, is defined as a
    136         // sequence of tokens, where each token is a header name, and the
    137         // token "close" has the above-mentioned additional meaning.
    138         //
    139         // To get through this mess, we treat the "Proxy-Connection" header
    140         // in exactly the same way as the "Connection" header, but only if
    141         // the latter is missing. We scan the sequence of tokens for both
    142         // "close" and "keep-alive". As "close" is specified by RFC 2068,
    143         // it takes precedence and indicates a non-persistent connection.
    144         // If there is no "close" but a "keep-alive", we take the hint.
    145 
    146         if (hit.hasNext()) {
    147             try {
    148                 TokenIterator ti = createTokenIterator(hit);
    149                 boolean keepalive = false;
    150                 while (ti.hasNext()) {
    151                     final String token = ti.nextToken();
    152                     if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
    153                         return false;
    154                     } else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
    155                         // continue the loop, there may be a "close" afterwards
    156                         keepalive = true;
    157                     }
    158                 }
    159                 if (keepalive)
    160                     return true;
    161                 // neither "close" nor "keep-alive", use default policy
    162 
    163             } catch (ParseException px) {
    164                 // invalid connection header means no persistent connection
    165                 // we don't have logging in HttpCore, so the exception is lost
    166                 return false;
    167             }
    168         }
    169 
    170         // default since HTTP/1.1 is persistent, before it was non-persistent
    171         return !ver.lessEquals(HttpVersion.HTTP_1_0);
    172     }
    173 
    174 
    175     /**
    176      * Creates a token iterator from a header iterator.
    177      * This method can be overridden to replace the implementation of
    178      * the token iterator.
    179      *
    180      * @param hit       the header iterator
    181      *
    182      * @return  the token iterator
    183      */
    184     protected TokenIterator createTokenIterator(HeaderIterator hit) {
    185         return new BasicTokenIterator(hit);
    186     }
    187 }
    188