Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge branch 'redirect_ok'

  • Loading branch information...
commit 533a32ad0149e2f1a9cfd5c9c35cbaf2bc02e0d4 2 parents da13182 + a1ef2e0
Akinori MUSHA knu authored
3  CHANGELOG.rdoc
View
@@ -10,6 +10,9 @@
in the current page. It works as expected when not passed a
string or regexp.
+ * Provide a way to only follow permanent redirects (301)
+ automatically: agent.redirect_ok = :permanent GH #73
+
* Bug Fixes:
* Fixed a bug where Referer is not sent when accessing a relative
18 lib/mechanize.rb
View
@@ -74,7 +74,14 @@ class Mechanize
attr_accessor :key
attr_accessor :cert
attr_accessor :pass
+
+ # Controls how this agent deals with redirects. If it is set to
+ # true or :all, all 3xx redirects are automatically followed. This
+ # is the default behavior. If it is :permanent, only 301 (Moved
+ # Permanently) redirects are followed. If it is a false value, no
+ # redirects are followed.
attr_accessor :redirect_ok
+
attr_accessor :gzip_enabled
attr_accessor :keep_alive_time
attr_accessor :keep_alive
@@ -133,7 +140,7 @@ def initialize
@cert = nil # OpenSSL Certificate
@key = nil # OpenSSL Private Key
@pass = nil # OpenSSL Password
- @redirect_ok = true # Should we follow redirects?
+ @redirect_ok = true
@gzip_enabled = true
# attr_readers
@@ -609,7 +616,14 @@ def fetch_page(params)
log.debug("Got cached page") if log
return visited_page(uri) || page
elsif res_klass <= Net::HTTPRedirection
- return page unless follow_redirect?
+ case redirect_ok
+ when true, :all
+ # shortcut
+ when false, nil
+ return page
+ when :permanent
+ return page if res_klass != Net::HTTPMovedPermanently
+ end
log.info("follow redirect to: #{ response['Location'] }") if log
from_uri = page.uri
raise RedirectLimitReachedError.new(page, redirects) if redirects + 1 > redirection_limit
1  test/helper.rb
View
@@ -47,6 +47,7 @@ def do_start
'/http_headers' => HeaderServlet,
'/infinite_redirect' => InfiniteRedirectTest,
'/infinite_refresh' => InfiniteRefreshTest,
+ '/redirect_ok' => RedirectOkTest,
'/redirect' => RedirectTest,
'/refresh_without_url' => RefreshWithoutUrl,
'/refresh_with_empty_url' => RefreshWithEmptyUrl,
23 test/servlets.rb
View
@@ -200,6 +200,29 @@ def do_GET(req, res)
alias :do_POST :do_GET
end
+class RedirectOkTest < WEBrick::HTTPServlet::AbstractServlet
+ def do_GET(req, res)
+ res['Content-Type'] = "text/plain"
+ case q = req.query['q']
+ when '1'..'2'
+ res.status = '301'
+ q.succ!
+ when '3'..'4'
+ res.status = '302'
+ q.succ!
+ when '5'
+ res.status = '200'
+ res.body = 'Finally OK.'
+ return
+ else
+ res.status = '301'
+ q = '1'
+ end
+ res['Location'] = "/redirect_ok?q=#{q}"
+ end
+ alias :do_POST :do_GET
+end
+
class RedirectTest < WEBrick::HTTPServlet::AbstractServlet
def do_GET(req, res)
res['Content-Type'] = req.query['ct'] || "text/html"
Please sign in to comment.
Something went wrong with that request. Please try again.