View Javadoc

1   package com.atlassian.httpclient.apache.httpcomponents;
2   
3   import org.apache.http.HttpEntityEnclosingRequest;
4   import org.apache.http.HttpRequest;
5   import org.apache.http.HttpResponse;
6   import org.apache.http.ProtocolException;
7   import org.apache.http.client.methods.HttpDelete;
8   import org.apache.http.client.methods.HttpGet;
9   import org.apache.http.client.methods.HttpHead;
10  import org.apache.http.client.methods.HttpPatch;
11  import org.apache.http.client.methods.HttpPost;
12  import org.apache.http.client.methods.HttpPut;
13  import org.apache.http.client.methods.HttpUriRequest;
14  import org.apache.http.impl.client.DefaultRedirectStrategy;
15  import org.apache.http.protocol.HttpContext;
16  
17  import java.net.URI;
18  
19  public class RedirectStrategy extends DefaultRedirectStrategy {
20      final String[] REDIRECT_METHODS = {HttpHead.METHOD_NAME, HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpPut.METHOD_NAME, HttpDelete.METHOD_NAME, HttpPatch.METHOD_NAME};
21  
22      @Override
23      public boolean isRedirectable(String method) {
24          for (String m : REDIRECT_METHODS) {
25              if (m.equalsIgnoreCase(method)) {
26                  return true;
27              }
28          }
29          return false;
30      }
31  
32      @Override
33      public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context)
34              throws ProtocolException {
35          URI uri = getLocationURI(request, response, context);
36          String method = request.getRequestLine().getMethod();
37          if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
38              return new HttpHead(uri);
39          } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
40              return new HttpGet(uri);
41          } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
42              final HttpPost post = new HttpPost(uri);
43              if (request instanceof HttpEntityEnclosingRequest) {
44                  post.setEntity(((HttpEntityEnclosingRequest) request).getEntity());
45              }
46              return post;
47          } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
48              return new HttpPut(uri);
49          } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
50              return new HttpDelete(uri);
51          } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
52              return new HttpPatch(uri);
53          } else {
54              return new HttpGet(uri);
55          }
56      }
57  }