Monday, October 29, 2012

Resolve an HTTP Redirect

// source: https://gist.github.com/3899754

def findRealUrl(url) {
    HttpURLConnection conn = url.openConnection()
    conn.followRedirects = false
    conn.requestMethod = 'HEAD'
    if(conn.responseCode in [301,302]) {
        if (conn.headerFields.'Location') {
          return findRealUrl(conn.headerFields.Location.first().toURL())
        } else {
            throw new RuntimeException('Failed to follow redirect')
        }
    }
    return url
}

No comments:

Post a Comment