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