Home | History | Annotate | Download | only in protocol
      1 /*
      2  * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/client/protocol/RequestAddCookies.java $
      3  * $Revision: 673450 $
      4  * $Date: 2008-07-02 10:35:05 -0700 (Wed, 02 Jul 2008) $
      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.client.protocol;
     33 
     34 import java.io.IOException;
     35 import java.net.URI;
     36 import java.net.URISyntaxException;
     37 import java.util.ArrayList;
     38 import java.util.List;
     39 
     40 import org.apache.commons.logging.Log;
     41 import org.apache.commons.logging.LogFactory;
     42 import org.apache.http.Header;
     43 import org.apache.http.HttpException;
     44 import org.apache.http.HttpHost;
     45 import org.apache.http.HttpRequest;
     46 import org.apache.http.HttpRequestInterceptor;
     47 import org.apache.http.ProtocolException;
     48 import org.apache.http.client.CookieStore;
     49 import org.apache.http.client.methods.HttpUriRequest;
     50 import org.apache.http.client.params.HttpClientParams;
     51 import org.apache.http.conn.ManagedClientConnection;
     52 import org.apache.http.cookie.Cookie;
     53 import org.apache.http.cookie.CookieOrigin;
     54 import org.apache.http.cookie.CookieSpec;
     55 import org.apache.http.cookie.CookieSpecRegistry;
     56 import org.apache.http.protocol.HttpContext;
     57 import org.apache.http.protocol.ExecutionContext;
     58 
     59 /**
     60  * Request interceptor that matches cookies available in the current
     61  * {@link CookieStore} to the request being executed and generates
     62  * corresponding cookierequest headers.
     63  *
     64  * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
     65  *
     66  * @version $Revision: 673450 $
     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 RequestAddCookies implements HttpRequestInterceptor {
     76 
     77     private final Log log = LogFactory.getLog(getClass());
     78 
     79     public RequestAddCookies() {
     80         super();
     81     }
     82 
     83     public void process(final HttpRequest request, final HttpContext context)
     84             throws HttpException, IOException {
     85         if (request == null) {
     86             throw new IllegalArgumentException("HTTP request may not be null");
     87         }
     88         if (context == null) {
     89             throw new IllegalArgumentException("HTTP context may not be null");
     90         }
     91 
     92         // Obtain cookie store
     93         CookieStore cookieStore = (CookieStore) context.getAttribute(
     94                 ClientContext.COOKIE_STORE);
     95         if (cookieStore == null) {
     96             this.log.info("Cookie store not available in HTTP context");
     97             return;
     98         }
     99 
    100         // Obtain the registry of cookie specs
    101         CookieSpecRegistry registry= (CookieSpecRegistry) context.getAttribute(
    102                 ClientContext.COOKIESPEC_REGISTRY);
    103         if (registry == null) {
    104             this.log.info("CookieSpec registry not available in HTTP context");
    105             return;
    106         }
    107 
    108         // Obtain the target host (required)
    109         HttpHost targetHost = (HttpHost) context.getAttribute(
    110                 ExecutionContext.HTTP_TARGET_HOST);
    111         if (targetHost == null) {
    112             throw new IllegalStateException("Target host not specified in HTTP context");
    113         }
    114 
    115         // Obtain the client connection (required)
    116         ManagedClientConnection conn = (ManagedClientConnection) context.getAttribute(
    117                 ExecutionContext.HTTP_CONNECTION);
    118         if (conn == null) {
    119             throw new IllegalStateException("Client connection not specified in HTTP context");
    120         }
    121 
    122         String policy = HttpClientParams.getCookiePolicy(request.getParams());
    123         if (this.log.isDebugEnabled()) {
    124             this.log.debug("CookieSpec selected: " + policy);
    125         }
    126 
    127         URI requestURI;
    128         if (request instanceof HttpUriRequest) {
    129             requestURI = ((HttpUriRequest) request).getURI();
    130         } else {
    131             try {
    132                 requestURI = new URI(request.getRequestLine().getUri());
    133             } catch (URISyntaxException ex) {
    134                 throw new ProtocolException("Invalid request URI: " +
    135                         request.getRequestLine().getUri(), ex);
    136             }
    137         }
    138 
    139         String hostName = targetHost.getHostName();
    140         int port = targetHost.getPort();
    141         if (port < 0) {
    142             port = conn.getRemotePort();
    143         }
    144 
    145         CookieOrigin cookieOrigin = new CookieOrigin(
    146                 hostName,
    147                 port,
    148                 requestURI.getPath(),
    149                 conn.isSecure());
    150 
    151         // Get an instance of the selected cookie policy
    152         CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
    153         // Get all cookies available in the HTTP state
    154         List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
    155         // Find cookies matching the given origin
    156         List<Cookie> matchedCookies = new ArrayList<Cookie>();
    157         for (Cookie cookie : cookies) {
    158             if (cookieSpec.match(cookie, cookieOrigin)) {
    159                 if (this.log.isDebugEnabled()) {
    160                     this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
    161                 }
    162                 matchedCookies.add(cookie);
    163             }
    164         }
    165         // Generate Cookie request headers
    166         if (!matchedCookies.isEmpty()) {
    167             List<Header> headers = cookieSpec.formatCookies(matchedCookies);
    168             for (Header header : headers) {
    169                 request.addHeader(header);
    170             }
    171         }
    172 
    173         int ver = cookieSpec.getVersion();
    174         if (ver > 0) {
    175             boolean needVersionHeader = false;
    176             for (Cookie cookie : matchedCookies) {
    177                 if (ver != cookie.getVersion()) {
    178                     needVersionHeader = true;
    179                 }
    180             }
    181 
    182             if (needVersionHeader) {
    183                 Header header = cookieSpec.getVersionHeader();
    184                 if (header != null) {
    185                     // Advertise cookie version support
    186                     request.addHeader(header);
    187                 }
    188             }
    189         }
    190 
    191         // Stick the CookieSpec and CookieOrigin instances to the HTTP context
    192         // so they could be obtained by the response interceptor
    193         context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec);
    194         context.setAttribute(ClientContext.COOKIE_ORIGIN, cookieOrigin);
    195     }
    196 
    197 }
    198