Skip to content

Instantly share code, notes, and snippets.

@johnnywey
Created May 2, 2012 16:46
Show Gist options
  • Save johnnywey/2578109 to your computer and use it in GitHub Desktop.
Save johnnywey/2578109 to your computer and use it in GitHub Desktop.
Make HTTPBuilder Follow 302 Redirects Initiated by an HTTP POST
/*
* 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
}
@johnnywey
Copy link
Author

Modified to call the super class method first rather than simply look at the status code.

@jeff-xoom
Copy link

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