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.client;
29  
30  import java.net.URI;
31  import java.net.URISyntaxException;
32  
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.http.Header;
36  import org.apache.http.HttpHost;
37  import org.apache.http.HttpRequest;
38  import org.apache.http.HttpResponse;
39  import org.apache.http.HttpStatus;
40  import org.apache.http.ProtocolException;
41  import org.apache.http.annotation.Contract;
42  import org.apache.http.annotation.ThreadingBehavior;
43  import org.apache.http.client.CircularRedirectException;
44  import org.apache.http.client.RedirectHandler;
45  import org.apache.http.client.methods.HttpGet;
46  import org.apache.http.client.methods.HttpHead;
47  import org.apache.http.client.params.ClientPNames;
48  import org.apache.http.client.utils.URIUtils;
49  import org.apache.http.params.HttpParams;
50  import org.apache.http.protocol.ExecutionContext;
51  import org.apache.http.protocol.HttpContext;
52  import org.apache.http.util.Args;
53  import org.apache.http.util.Asserts;
54  
55  /**
56   * Default implementation of {@link RedirectHandler}.
57   *
58   * @since 4.0
59   *
60   * @deprecated (4.1)  use {@link DefaultRedirectStrategy}.
61   */
62  @Contract(threading = ThreadingBehavior.IMMUTABLE)
63  @Deprecated
64  public class DefaultRedirectHandler implements RedirectHandler {
65  
66      private final Log log = LogFactory.getLog(getClass());
67  
68      private static final String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
69  
70      public DefaultRedirectHandler() {
71          super();
72      }
73  
74      @Override
75      public boolean isRedirectRequested(
76              final HttpResponse response,
77              final HttpContext context) {
78          Args.notNull(response, "HTTP response");
79  
80          final int statusCode = response.getStatusLine().getStatusCode();
81          switch (statusCode) {
82          case HttpStatus.SC_MOVED_TEMPORARILY:
83          case HttpStatus.SC_MOVED_PERMANENTLY:
84          case HttpStatus.SC_TEMPORARY_REDIRECT:
85              final HttpRequest request = (HttpRequest) context.getAttribute(
86                      ExecutionContext.HTTP_REQUEST);
87              final String method = request.getRequestLine().getMethod();
88              return method.equalsIgnoreCase(HttpGet.METHOD_NAME)
89                  || method.equalsIgnoreCase(HttpHead.METHOD_NAME);
90          case HttpStatus.SC_SEE_OTHER:
91              return true;
92          default:
93              return false;
94          } //end of switch
95      }
96  
97      @Override
98      public URI getLocationURI(
99              final HttpResponse response,
100             final HttpContext context) throws ProtocolException {
101         Args.notNull(response, "HTTP response");
102         //get the location header to find out where to redirect to
103         final Header locationHeader = response.getFirstHeader("location");
104         if (locationHeader == null) {
105             // got a redirect response, but no location header
106             throw new ProtocolException(
107                     "Received redirect response " + response.getStatusLine()
108                     + " but no location header");
109         }
110         final String location = locationHeader.getValue();
111         if (this.log.isDebugEnabled()) {
112             this.log.debug("Redirect requested to location '" + location + "'");
113         }
114 
115         URI uri;
116         try {
117             uri = new URI(location);
118         } catch (final URISyntaxException ex) {
119             throw new ProtocolException("Invalid redirect URI: " + location, ex);
120         }
121 
122         final HttpParams params = response.getParams();
123         // rfc2616 demands the location value be a complete URI
124         // Location       = "Location" ":" absoluteURI
125         if (!uri.isAbsolute()) {
126             if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
127                 throw new ProtocolException("Relative redirect location '"
128                         + uri + "' not allowed");
129             }
130             // Adjust location URI
131             final HttpHost target = (HttpHost) context.getAttribute(
132                     ExecutionContext.HTTP_TARGET_HOST);
133             Asserts.notNull(target, "Target host");
134 
135             final HttpRequest request = (HttpRequest) context.getAttribute(
136                     ExecutionContext.HTTP_REQUEST);
137 
138             try {
139                 final URI requestURI = new URI(request.getRequestLine().getUri());
140                 final URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
141                 uri = URIUtils.resolve(absoluteRequestURI, uri);
142             } catch (final URISyntaxException ex) {
143                 throw new ProtocolException(ex.getMessage(), ex);
144             }
145         }
146 
147         if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {
148 
149             RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(
150                     REDIRECT_LOCATIONS);
151 
152             if (redirectLocations == null) {
153                 redirectLocations = new RedirectLocations();
154                 context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
155             }
156 
157             final URI redirectURI;
158             if (uri.getFragment() != null) {
159                 try {
160                     final HttpHost target = new HttpHost(
161                             uri.getHost(),
162                             uri.getPort(),
163                             uri.getScheme());
164                     redirectURI = URIUtils.rewriteURI(uri, target, true);
165                 } catch (final URISyntaxException ex) {
166                     throw new ProtocolException(ex.getMessage(), ex);
167                 }
168             } else {
169                 redirectURI = uri;
170             }
171 
172             if (redirectLocations.contains(redirectURI)) {
173                 throw new CircularRedirectException("Circular redirect to '" +
174                         redirectURI + "'");
175             } else {
176                 redirectLocations.add(redirectURI);
177             }
178         }
179 
180         return uri;
181     }
182 
183 }