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.http.impl.execchain;
29  
30  import java.io.IOException;
31  import java.net.URI;
32  import java.util.List;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.http.HttpEntityEnclosingRequest;
37  import org.apache.http.HttpException;
38  import org.apache.http.HttpHost;
39  import org.apache.http.HttpRequest;
40  import org.apache.http.ProtocolException;
41  import org.apache.http.annotation.ThreadSafe;
42  import org.apache.http.auth.AuthScheme;
43  import org.apache.http.auth.AuthState;
44  import org.apache.http.client.RedirectException;
45  import org.apache.http.client.RedirectStrategy;
46  import org.apache.http.client.config.RequestConfig;
47  import org.apache.http.client.methods.CloseableHttpResponse;
48  import org.apache.http.client.methods.HttpExecutionAware;
49  import org.apache.http.client.methods.HttpRequestWrapper;
50  import org.apache.http.client.protocol.HttpClientContext;
51  import org.apache.http.client.utils.URIUtils;
52  import org.apache.http.conn.routing.HttpRoute;
53  import org.apache.http.conn.routing.HttpRoutePlanner;
54  import org.apache.http.util.Args;
55  import org.apache.http.util.EntityUtils;
56  
57  /**
58   * Request executor in the request execution chain that is responsible
59   * for handling of request redirects.
60   * <p/>
61   * Further responsibilities such as communication with the opposite
62   * endpoint is delegated to the next executor in the request execution
63   * chain.
64   *
65   * @since 4.3
66   */
67  @ThreadSafe
68  public class RedirectExec implements ClientExecChain {
69  
70      private final Log log = LogFactory.getLog(getClass());
71  
72      private final ClientExecChain requestExecutor;
73      private final RedirectStrategy redirectStrategy;
74      private final HttpRoutePlanner routePlanner;
75  
76      public RedirectExec(
77              final ClientExecChain requestExecutor,
78              final HttpRoutePlanner routePlanner,
79              final RedirectStrategy redirectStrategy) {
80          super();
81          Args.notNull(requestExecutor, "HTTP client request executor");
82          Args.notNull(routePlanner, "HTTP route planner");
83          Args.notNull(redirectStrategy, "HTTP redirect strategy");
84          this.requestExecutor = requestExecutor;
85          this.routePlanner = routePlanner;
86          this.redirectStrategy = redirectStrategy;
87      }
88  
89      @Override
90      public CloseableHttpResponse execute(
91              final HttpRoute route,
92              final HttpRequestWrapper request,
93              final HttpClientContext context,
94              final HttpExecutionAware execAware) throws IOException, HttpException {
95          Args.notNull(route, "HTTP route");
96          Args.notNull(request, "HTTP request");
97          Args.notNull(context, "HTTP context");
98  
99          final List<URI> redirectLocations = context.getRedirectLocations();
100         if (redirectLocations != null) {
101             redirectLocations.clear();
102         }
103 
104         final RequestConfig config = context.getRequestConfig();
105         final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
106         HttpRoute currentRoute = route;
107         HttpRequestWrapper currentRequest = request;
108         for (int redirectCount = 0;;) {
109             final CloseableHttpResponse response = requestExecutor.execute(
110                     currentRoute, currentRequest, context, execAware);
111             try {
112                 if (config.isRedirectsEnabled() &&
113                         this.redirectStrategy.isRedirected(currentRequest, response, context)) {
114 
115                     if (redirectCount >= maxRedirects) {
116                         throw new RedirectException("Maximum redirects ("+ maxRedirects + ") exceeded");
117                     }
118                     redirectCount++;
119 
120                     final HttpRequest redirect = this.redirectStrategy.getRedirect(
121                             currentRequest, response, context);
122                     if (!redirect.headerIterator().hasNext()) {
123                         final HttpRequest original = request.getOriginal();
124                         redirect.setHeaders(original.getAllHeaders());
125                     }
126                     currentRequest = HttpRequestWrapper.wrap(redirect);
127 
128                     if (currentRequest instanceof HttpEntityEnclosingRequest) {
129                         RequestEntityProxy.enhance((HttpEntityEnclosingRequest) currentRequest);
130                     }
131 
132                     final URI uri = currentRequest.getURI();
133                     final HttpHost newTarget = URIUtils.extractHost(uri);
134                     if (newTarget == null) {
135                         throw new ProtocolException("Redirect URI does not specify a valid host name: " +
136                                 uri);
137                     }
138 
139                     // Reset virtual host and auth states if redirecting to another host
140                     if (!currentRoute.getTargetHost().equals(newTarget)) {
141                         final AuthState targetAuthState = context.getTargetAuthState();
142                         if (targetAuthState != null) {
143                             this.log.debug("Resetting target auth state");
144                             targetAuthState.reset();
145                         }
146                         final AuthState proxyAuthState = context.getProxyAuthState();
147                         if (proxyAuthState != null) {
148                             final AuthScheme authScheme = proxyAuthState.getAuthScheme();
149                             if (authScheme != null && authScheme.isConnectionBased()) {
150                                 this.log.debug("Resetting proxy auth state");
151                                 proxyAuthState.reset();
152                             }
153                         }
154                     }
155 
156                     currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context);
157                     if (this.log.isDebugEnabled()) {
158                         this.log.debug("Redirecting to '" + uri + "' via " + currentRoute);
159                     }
160                     EntityUtils.consume(response.getEntity());
161                     response.close();
162                 } else {
163                     return response;
164                 }
165             } catch (final RuntimeException ex) {
166                 response.close();
167                 throw ex;
168             } catch (final IOException ex) {
169                 response.close();
170                 throw ex;
171             } catch (final HttpException ex) {
172                 // Protocol exception related to a direct.
173                 // The underlying connection may still be salvaged.
174                 try {
175                     EntityUtils.consume(response.getEntity());
176                 } catch (final IOException ioex) {
177                     this.log.debug("I/O error while releasing connection", ioex);
178                 } finally {
179                     response.close();
180                 }
181                 throw ex;
182             }
183         }
184     }
185 
186 }