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