Created
May 2, 2012 16:46
-
-
Save johnnywey/2578109 to your computer and use it in GitHub Desktop.
Make HTTPBuilder Follow 302 Redirects Initiated by an HTTP POST
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* HTTPBuilder uses HttpClient and does not automatically follow HTTP 302 responses from a POST as per the HTTP spec. You can modify this | |
* behavior by overriding updating the default behavior to follow regardless of initiating method. | |
*/ | |
def http = new HTTPBuilder("http://UrlThatExpectsAPostAndReturnsA302.com") | |
http.client.setRedirectStrategy(new DefaultRedirectStrategy() { | |
@Override | |
boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) { | |
def redirected = super.isRedirected(request, response, context) | |
return redirected || response.getStatusLine().getStatusCode() == 302 | |
} | |
}) | |
def postBody = ['param':'value'] | |
// Then you can do: | |
def html = http.request(POST) { | |
uri.path = '/POST' | |
send URLENC, postBody | |
} |
Thanks. As of 4.2 (Apache HttpClient) there is a LaxRedirectStrategy class that allows redirects for POST requests in addition to GET and HEAD requests.
So, the above code can now simply be:
def http = new HTTPBuilder("http://UrlThatExpectsAPostAndReturnsA302.com")
http.client.setRedirectStrategy(new LaxRedirectStrategy())
def postBody = ['param':'value']
// Then you can do:
def html = http.request(POST) {
uri.path = '/POST'
send URLENC, postBody
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modified to call the super class method first rather than simply look at the status code.