Class: Mechanize::HTTP::Agent
- Inherits:
-
Object
- Object
- Mechanize::HTTP::Agent
- Defined in:
- lib/mechanize/http/agent.rb
Overview
An HTTP (and local disk access) user agent. This class is an implementation detail and is subject to change at any time.
Instance Attribute Summary collapse
-
#auth_store ⇒ Object
readonly
:section: HTTP Authentication.
-
#authenticate_methods ⇒ Object
readonly
:nodoc:.
-
#conditional_requests ⇒ Object
Disables If-Modified-Since conditional requests (enabled by default).
-
#content_encoding_hooks ⇒ Object
readonly
A list of hooks to call to handle the content-encoding of a request.
-
#context ⇒ Object
The context parses responses into pages.
-
#cookie_jar ⇒ Object
The cookies for this agent.
-
#digest_challenges ⇒ Object
readonly
:nodoc:.
-
#follow_meta_refresh ⇒ Object
Follow HTML meta refresh and HTTP Refresh.
-
#follow_meta_refresh_self ⇒ Object
Follow an HTML meta refresh that has no “url=” in the content attribute.
-
#gzip_enabled ⇒ Object
Is gzip compression of requests enabled?.
-
#history ⇒ Object
history of requests made.
-
#http ⇒ Object
readonly
:nodoc:.
-
#keep_alive ⇒ Object
Set to false to disable HTTP/1.1 keep-alive requests.
-
#max_file_buffer ⇒ Object
Responses larger than this will be written to a Tempfile instead of stored in memory.
-
#open_timeout ⇒ Object
Length of time to wait until a connection is opened in seconds.
-
#pass ⇒ Object
OpenSSL key password.
-
#post_connect_hooks ⇒ Object
readonly
A list of hooks to call after retrieving a response.
-
#pre_connect_hooks ⇒ Object
readonly
A list of hooks to call before making a request.
-
#read_timeout ⇒ Object
Length of time to attempt to read data from the server.
-
#redirect_ok ⇒ Object
Controls how this agent deals with redirects.
-
#redirection_limit ⇒ Object
Maximum number of redirects to follow.
-
#request_headers ⇒ Object
A hash of request headers to be used for every request.
-
#robots ⇒ Object
When true, this agent will consult the site’s robots.txt for each access.
-
#scheme_handlers ⇒ Object
Handlers for various URI schemes.
-
#user_agent ⇒ Object
The User-Agent header to send.
Instance Method Summary collapse
-
#add_auth(uri, user, password, realm = nil, domain = nil) ⇒ Object
Adds credentials
user,passforuri. -
#add_default_auth(user, password, domain = nil) ⇒ Object
USE OF add_default_auth IS NOT RECOMMENDED AS IT MAY EXPOSE PASSWORDS TO THIRD PARTIES.
-
#auto_io(name, read_size, input_io) ⇒ Object
Creates a new output IO by reading
input_ioinread_sizechunks. -
#back ⇒ Object
Equivalent to the browser back button.
-
#ca_file ⇒ Object
Path to an OpenSSL CA certificate file.
-
#ca_file=(ca_file) ⇒ Object
Sets the path to an OpenSSL CA certificate file.
-
#cert_store ⇒ Object
The SSL certificate store used for validating connections.
-
#cert_store=(cert_store) ⇒ Object
Sets the SSL certificate store used for validating connections.
-
#certificate ⇒ Object
The client X509 certificate.
-
#certificate=(certificate) ⇒ Object
Sets the client certificate to given X509 certificate.
-
#connection_for(uri) ⇒ Object
:section: Request.
-
#content_encoding_gunzip(body_io) ⇒ Object
Decodes a gzip-encoded
body_io. -
#content_encoding_inflate(body_io) ⇒ Object
Decodes a deflate-encoded
body_io. -
#current_page ⇒ Object
Returns the latest page loaded by the agent.
- #disable_keep_alive(request) ⇒ Object
- #enable_gzip(request) ⇒ Object
-
#fetch(uri, method = :get, headers = {}, params = [], referer = current_page, redirects = 0) ⇒ Object
Retrieves
uriand parses it into a page or other object according to PluggableParser. -
#get_meta_refresh(response, uri, page) ⇒ Object
:section: Response.
-
#get_robots(uri) ⇒ Object
:section: Robots.
-
#hook_content_encoding(response, uri, response_body_io) ⇒ Object
:section: Hooks.
- #http_request(uri, method, params = nil) ⇒ Object
-
#idle_timeout ⇒ Object
Reset connections that have not been used in this many seconds.
-
#idle_timeout=(timeout) ⇒ Object
Sets the connection idle timeout for persistent connections.
- #inflate(compressed, window_bits = nil) ⇒ Object
-
#initialize ⇒ Agent
constructor
Creates a new Mechanize HTTP user agent.
- #log ⇒ Object
- #max_history ⇒ Object
- #max_history=(length) ⇒ Object
-
#post_connect(uri, response, body_io) ⇒ Object
Invokes hooks added to post_connect_hooks after a
responseis returned and the responsebodyis handled. -
#pre_connect(request) ⇒ Object
Invokes hooks added to pre_connect_hooks before a
requestis made. -
#private_key ⇒ Object
An OpenSSL private key or the path to a private key.
-
#private_key=(private_key) ⇒ Object
Sets the client’s private key.
-
#proxy_uri ⇒ Object
URI for a proxy connection.
- #request_add_headers(request, headers = {}) ⇒ Object
- #request_auth(request, uri) ⇒ Object
- #request_auth_digest(request, uri, realm, base_uri, iis) ⇒ Object
- #request_cookies(request, uri) ⇒ Object
- #request_host(request, uri) ⇒ Object
- #request_language_charset(request) ⇒ Object
-
#request_log(request) ⇒ Object
Log specified headers for the request.
-
#request_referer(request, uri, referer) ⇒ Object
Sets a Referer header.
- #request_user_agent(request) ⇒ Object
- #resolve(uri, referer = current_page) ⇒ Object
- #resolve_parameters(uri, method, parameters) ⇒ Object
- #response_authenticate(response, page, uri, request, headers, params, referer) ⇒ Object
- #response_content_encoding(response, body_io) ⇒ Object
- #response_cookies(response, uri, page) ⇒ Object
- #response_follow_meta_refresh(response, uri, page, redirects) ⇒ Object
- #response_log(response) ⇒ Object
- #response_parse(response, body_io, uri) ⇒ Object
- #response_read(response, request, uri) ⇒ Object
- #response_redirect(response, method, page, redirects, referer = current_page) ⇒ Object
-
#retry_change_requests ⇒ Object
Retry non-idempotent requests?.
-
#retry_change_requests=(retri) ⇒ Object
Retry non-idempotent requests.
-
#robots_allowed?(uri) ⇒ Boolean
Tests if this agent is allowed to access
url, consulting the site’s robots.txt. -
#robots_disallowed?(url) ⇒ Boolean
Opposite of robots_allowed?.
-
#robots_error(url) ⇒ Object
Returns an error object if there is an error in fetching or parsing robots.txt of the site
url. -
#robots_error!(url) ⇒ Object
Raises the error if there is an error in fetching or parsing robots.txt of the site
url. -
#robots_reset(url) ⇒ Object
Removes robots.txt cache for the site
url. - #save_cookies(uri, set_cookie) ⇒ Object
-
#set_proxy(addr, port, user = nil, pass = nil) ⇒ Object
Sets the proxy address, port, user, and password
addrshould be a host, with no “http://”,portmay be a port number, service name or port number string. -
#ssl_version ⇒ Object
SSL version to use.
-
#ssl_version=(ssl_version) ⇒ Object
Sets the SSL version to use.
- #use_tempfile?(size) ⇒ Boolean
-
#verify_callback ⇒ Object
A callback for additional certificate verification.
-
#verify_callback=(verify_callback) ⇒ Object
Sets the certificate verify callback.
-
#verify_mode ⇒ Object
How to verify SSL connections.
-
#verify_mode=(verify_mode) ⇒ Object
Sets the mode for verifying SSL connections.
-
#visited_page(url) ⇒ Object
Returns a visited page for the url passed in, otherwise nil.
- #webrobots ⇒ Object
Constructor Details
#initialize ⇒ Agent
Creates a new Mechanize HTTP user agent. The user agent is an implementation detail of mechanize and its API may change at any time.
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/mechanize/http/agent.rb', line 117 def initialize @conditional_requests = true @context = nil @content_encoding_hooks = [] @cookie_jar = Mechanize::CookieJar.new @follow_meta_refresh = false @follow_meta_refresh_self = false @gzip_enabled = true @history = Mechanize::History.new @keep_alive = true @max_file_buffer = 100_000 # 5MB for response bodies @open_timeout = nil @post_connect_hooks = [] @pre_connect_hooks = [] @read_timeout = nil @redirect_ok = true @redirection_limit = 20 @request_headers = {} @robots = false @user_agent = nil @webrobots = nil # HTTP Authentication @auth_store = Mechanize::HTTP::AuthStore.new @authenticate_parser = Mechanize::HTTP::WWWAuthenticateParser.new @authenticate_methods = Hash.new do |methods, uri| methods[uri] = Hash.new do |realms, auth_scheme| realms[auth_scheme] = [] end end @digest_auth = Net::HTTP::DigestAuth.new @digest_challenges = {} # SSL @pass = nil @scheme_handlers = Hash.new { |h, scheme| h[scheme] = lambda { |link, page| raise Mechanize::UnsupportedSchemeError, scheme } } @scheme_handlers['http'] = lambda { |link, page| link } @scheme_handlers['https'] = @scheme_handlers['http'] @scheme_handlers['relative'] = @scheme_handlers['http'] @scheme_handlers['file'] = @scheme_handlers['http'] @http = Net::HTTP::Persistent.new 'mechanize' @http.idle_timeout = 5 @http.keep_alive = 300 end |
Instance Attribute Details
#auth_store ⇒ Object (readonly)
:section: HTTP Authentication
46 47 48 |
# File 'lib/mechanize/http/agent.rb', line 46 def auth_store @auth_store end |
#authenticate_methods ⇒ Object (readonly)
:nodoc:
47 48 49 |
# File 'lib/mechanize/http/agent.rb', line 47 def authenticate_methods @authenticate_methods end |
#conditional_requests ⇒ Object
Disables If-Modified-Since conditional requests (enabled by default)
15 16 17 |
# File 'lib/mechanize/http/agent.rb', line 15 def conditional_requests @conditional_requests end |
#content_encoding_hooks ⇒ Object (readonly)
A list of hooks to call to handle the content-encoding of a request.
42 43 44 |
# File 'lib/mechanize/http/agent.rb', line 42 def content_encoding_hooks @content_encoding_hooks end |
#context ⇒ Object
The context parses responses into pages
105 106 107 |
# File 'lib/mechanize/http/agent.rb', line 105 def context @context end |
#cookie_jar ⇒ Object
The cookies for this agent
96 97 98 |
# File 'lib/mechanize/http/agent.rb', line 96 def @cookie_jar end |
#digest_challenges ⇒ Object (readonly)
:nodoc:
48 49 50 |
# File 'lib/mechanize/http/agent.rb', line 48 def digest_challenges @digest_challenges end |
#follow_meta_refresh ⇒ Object
Follow HTML meta refresh and HTTP Refresh. If set to :anywhere meta refresh tags outside of the head element will be followed.
54 55 56 |
# File 'lib/mechanize/http/agent.rb', line 54 def @follow_meta_refresh end |
#follow_meta_refresh_self ⇒ Object
Follow an HTML meta refresh that has no “url=” in the content attribute.
Defaults to false to prevent infinite refresh loops.
59 60 61 |
# File 'lib/mechanize/http/agent.rb', line 59 def @follow_meta_refresh_self end |
#gzip_enabled ⇒ Object
Is gzip compression of requests enabled?
18 19 20 |
# File 'lib/mechanize/http/agent.rb', line 18 def gzip_enabled @gzip_enabled end |
#history ⇒ Object
history of requests made
29 30 31 |
# File 'lib/mechanize/http/agent.rb', line 29 def history @history end |
#http ⇒ Object (readonly)
:nodoc:
107 108 109 |
# File 'lib/mechanize/http/agent.rb', line 107 def http @http end |
#keep_alive ⇒ Object
Set to false to disable HTTP/1.1 keep-alive requests
85 86 87 |
# File 'lib/mechanize/http/agent.rb', line 85 def keep_alive @keep_alive end |
#max_file_buffer ⇒ Object
Responses larger than this will be written to a Tempfile instead of stored in memory. Setting this to nil disables creation of Tempfiles.
100 101 102 |
# File 'lib/mechanize/http/agent.rb', line 100 def max_file_buffer @max_file_buffer end |
#open_timeout ⇒ Object
Length of time to wait until a connection is opened in seconds
88 89 90 |
# File 'lib/mechanize/http/agent.rb', line 88 def open_timeout @open_timeout end |
#pass ⇒ Object
OpenSSL key password
80 81 82 |
# File 'lib/mechanize/http/agent.rb', line 80 def pass @pass end |
#post_connect_hooks ⇒ Object (readonly)
A list of hooks to call after retrieving a response. Hooks are called with the agent and the response returned.
35 36 37 |
# File 'lib/mechanize/http/agent.rb', line 35 def post_connect_hooks @post_connect_hooks end |
#pre_connect_hooks ⇒ Object (readonly)
A list of hooks to call before making a request. Hooks are called with the agent and the request to be performed.
39 40 41 |
# File 'lib/mechanize/http/agent.rb', line 39 def pre_connect_hooks @pre_connect_hooks end |
#read_timeout ⇒ Object
Length of time to attempt to read data from the server
91 92 93 |
# File 'lib/mechanize/http/agent.rb', line 91 def read_timeout @read_timeout end |
#redirect_ok ⇒ Object
Controls how this agent deals with redirects. The following values are allowed:
- :all, true
-
All 3xx redirects are followed (default)
- :permanent
-
Only 301 Moved Permanantly redirects are followed
- false
-
No redirects are followed
67 68 69 |
# File 'lib/mechanize/http/agent.rb', line 67 def redirect_ok @redirect_ok end |
#redirection_limit ⇒ Object
Maximum number of redirects to follow
70 71 72 |
# File 'lib/mechanize/http/agent.rb', line 70 def redirection_limit @redirection_limit end |
#request_headers ⇒ Object
A hash of request headers to be used for every request
21 22 23 |
# File 'lib/mechanize/http/agent.rb', line 21 def request_headers @request_headers end |
#robots ⇒ Object
When true, this agent will consult the site’s robots.txt for each access.
75 76 77 |
# File 'lib/mechanize/http/agent.rb', line 75 def robots @robots end |
#scheme_handlers ⇒ Object
Handlers for various URI schemes
110 111 112 |
# File 'lib/mechanize/http/agent.rb', line 110 def scheme_handlers @scheme_handlers end |
#user_agent ⇒ Object
The User-Agent header to send
24 25 26 |
# File 'lib/mechanize/http/agent.rb', line 24 def user_agent @user_agent end |
Instance Method Details
#add_auth(uri, user, password, realm = nil, domain = nil) ⇒ Object
Adds credentials user, pass for uri. If realm is set the credentials are used only for that realm. If realm is not set the credentials become the default for any realm on that URI.
domain and realm are exclusive as NTLM does not follow RFC 2617. If domain is given it is only used for NTLM authentication.
177 178 179 |
# File 'lib/mechanize/http/agent.rb', line 177 def add_auth uri, user, password, realm = nil, domain = nil @auth_store.add_auth uri, user, password, realm, domain end |
#add_default_auth(user, password, domain = nil) ⇒ Object
USE OF add_default_auth IS NOT RECOMMENDED AS IT MAY EXPOSE PASSWORDS TO THIRD PARTIES
Adds credentials user, pass as the default authentication credentials. If no other credentials are available these will be returned from credentials_for.
If domain is given it is only used for NTLM authentication.
191 192 193 |
# File 'lib/mechanize/http/agent.rb', line 191 def add_default_auth user, password, domain = nil # :nodoc: @auth_store.add_default_auth user, password, domain end |
#auto_io(name, read_size, input_io) ⇒ Object
Creates a new output IO by reading input_io in read_size chunks. If the output is over the max_file_buffer size a Tempfile with name is created.
If a block is provided, each chunk of input_io is yielded for further processing.
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 |
# File 'lib/mechanize/http/agent.rb', line 1085 def auto_io name, read_size, input_io out_io = StringIO.new out_io.set_encoding Encoding::BINARY if out_io.respond_to? :set_encoding until input_io.eof? do if StringIO === out_io and use_tempfile? out_io.size then new_io = Tempfile.new name new_io.unlink new_io.binmode new_io.write out_io.string out_io = new_io end chunk = input_io.read read_size chunk = yield chunk if block_given? out_io.write chunk end out_io.rewind out_io end |
#back ⇒ Object
Equivalent to the browser back button. Returns the most recent page visited.
323 324 325 |
# File 'lib/mechanize/http/agent.rb', line 323 def back @history.pop end |
#ca_file ⇒ Object
Path to an OpenSSL CA certificate file
976 977 978 |
# File 'lib/mechanize/http/agent.rb', line 976 def ca_file @http.ca_file end |
#ca_file=(ca_file) ⇒ Object
Sets the path to an OpenSSL CA certificate file
981 982 983 |
# File 'lib/mechanize/http/agent.rb', line 981 def ca_file= ca_file @http.ca_file = ca_file end |
#cert_store ⇒ Object
The SSL certificate store used for validating connections
986 987 988 |
# File 'lib/mechanize/http/agent.rb', line 986 def cert_store @http.cert_store end |
#cert_store=(cert_store) ⇒ Object
Sets the SSL certificate store used for validating connections
991 992 993 |
# File 'lib/mechanize/http/agent.rb', line 991 def cert_store= cert_store @http.cert_store = cert_store end |
#certificate ⇒ Object
The client X509 certificate
996 997 998 |
# File 'lib/mechanize/http/agent.rb', line 996 def certificate @http.certificate end |
#certificate=(certificate) ⇒ Object
Sets the client certificate to given X509 certificate. If a path is given the certificate will be loaded and set.
1002 1003 1004 1005 1006 1007 1008 1009 1010 |
# File 'lib/mechanize/http/agent.rb', line 1002 def certificate= certificate certificate = if OpenSSL::X509::Certificate === certificate then certificate else OpenSSL::X509::Certificate.new File.read certificate end @http.certificate = certificate end |
#connection_for(uri) ⇒ Object
:section: Request
384 385 386 387 388 389 390 391 |
# File 'lib/mechanize/http/agent.rb', line 384 def connection_for uri case uri.scheme.downcase when 'http', 'https' then return @http when 'file' then return Mechanize::FileConnection.new end end |
#content_encoding_gunzip(body_io) ⇒ Object
Decodes a gzip-encoded body_io. If it cannot be decoded, inflate is tried followed by raising an error.
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'lib/mechanize/http/agent.rb', line 397 def content_encoding_gunzip body_io log.debug('gzip response') if log zio = Zlib::GzipReader.new body_io out_io = auto_io 'mechanize-gunzip', 16384, zio zio.finish return out_io rescue Zlib::Error log.error('unable to gunzip response, trying raw inflate') if log body_io.rewind body_io.read 10 begin return inflate body_io, -Zlib::MAX_WBITS rescue Zlib::Error => e log.error("unable to gunzip response: #{e}") if log raise end ensure zio.close if zio and not zio.closed? body_io.close unless body_io.closed? end |
#content_encoding_inflate(body_io) ⇒ Object
Decodes a deflate-encoded body_io. If it cannot be decoded, raw inflate is tried followed by raising an error.
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
# File 'lib/mechanize/http/agent.rb', line 426 def content_encoding_inflate body_io log.debug('deflate body') if log return inflate body_io rescue Zlib::Error log.error('unable to inflate response, trying raw deflate') if log body_io.rewind begin return inflate body_io, -Zlib::MAX_WBITS rescue Zlib::Error => e log.error("unable to inflate response: #{e}") if log raise end ensure body_io.close end |
#current_page ⇒ Object
Returns the latest page loaded by the agent
330 331 332 |
# File 'lib/mechanize/http/agent.rb', line 330 def current_page @history.last end |
#disable_keep_alive(request) ⇒ Object
445 446 447 |
# File 'lib/mechanize/http/agent.rb', line 445 def disable_keep_alive request request['connection'] = 'close' unless @keep_alive end |
#enable_gzip(request) ⇒ Object
449 450 451 452 453 454 455 |
# File 'lib/mechanize/http/agent.rb', line 449 def enable_gzip request request['accept-encoding'] = if @gzip_enabled 'gzip,deflate,identity' else 'identity' end end |
#fetch(uri, method = :get, headers = {}, params = [], referer = current_page, redirects = 0) ⇒ Object
Retrieves uri and parses it into a page or other object according to PluggableParser. If the URI is an HTTP or HTTPS scheme URI the given HTTP method is used to retrieve it, along with the HTTP headers, request params and HTTP referer.
redirects tracks the number of redirects experienced when retrieving the page. If it is over the redirection_limit an error will be raised.
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
# File 'lib/mechanize/http/agent.rb', line 204 def fetch uri, method = :get, headers = {}, params = [], referer = current_page, redirects = 0 referer_uri = referer ? referer.uri : nil uri = resolve uri, referer uri, params = resolve_parameters uri, method, params request = http_request uri, method, params connection = connection_for uri request_auth request, uri disable_keep_alive request enable_gzip request request_language_charset request request, uri request_host request, uri request_referer request, uri, referer_uri request_user_agent request request_add_headers request, headers pre_connect request # Consult robots.txt if robots && uri.is_a?(URI::HTTP) robots_allowed?(uri) or raise Mechanize::RobotsDisallowedError.new(uri) end # Add If-Modified-Since if page is in history page = visited_page(uri) if (page = visited_page(uri)) and page.response['Last-Modified'] request['If-Modified-Since'] = page.response['Last-Modified'] end if(@conditional_requests) # Specify timeouts if given connection.open_timeout = @open_timeout if @open_timeout connection.read_timeout = @read_timeout if @read_timeout request_log request response_body_io = nil # Send the request response = connection.request(uri, request) { |res| response_log res response_body_io = response_read res, request, uri res } hook_content_encoding response, uri, response_body_io response_body_io = response_content_encoding response, response_body_io if request.response_body_permitted? post_connect uri, response, response_body_io page = response_parse response, response_body_io, uri response, uri, page = response, uri, page, redirects return if case response when Net::HTTPSuccess if robots && page.is_a?(Mechanize::Page) page.parser.noindex? and raise Mechanize::RobotsDisallowedError.new(uri) end page when Mechanize::FileResponse page when Net::HTTPNotModified log.debug("Got cached page") if log visited_page(uri) || page when Net::HTTPRedirection response_redirect response, method, page, redirects, referer when Net::HTTPUnauthorized response_authenticate(response, page, uri, request, headers, params, referer) else raise Mechanize::ResponseCodeError.new(page, 'unhandled response') end end |
#get_meta_refresh(response, uri, page) ⇒ Object
:section: Response
654 655 656 657 658 659 660 661 662 663 664 665 666 667 |
# File 'lib/mechanize/http/agent.rb', line 654 def response, uri, page return nil unless @follow_meta_refresh if page.respond_to?(:meta_refresh) and (redirect = page..first) then [redirect.delay, redirect.href] unless not @follow_meta_refresh_self and redirect.link_self elsif refresh = response['refresh'] delay, href, link_self = Mechanize::Page::MetaRefresh.parse refresh, uri raise Mechanize::Error, 'Invalid refresh http header' unless delay [delay.to_f, href] unless not @follow_meta_refresh_self and link_self end end |
#get_robots(uri) ⇒ Object
:section: Robots
923 924 925 926 927 928 |
# File 'lib/mechanize/http/agent.rb', line 923 def get_robots(uri) # :nodoc: fetch(uri).body rescue Mechanize::ResponseCodeError => e return '' if e.response_code == '404' raise e end |
#hook_content_encoding(response, uri, response_body_io) ⇒ Object
:section: Hooks
349 350 351 352 353 |
# File 'lib/mechanize/http/agent.rb', line 349 def hook_content_encoding response, uri, response_body_io @content_encoding_hooks.each do |hook| hook.call self, uri, response, response_body_io end end |
#http_request(uri, method, params = nil) ⇒ Object
457 458 459 460 461 462 463 464 465 466 467 468 469 |
# File 'lib/mechanize/http/agent.rb', line 457 def http_request uri, method, params = nil case uri.scheme.downcase when 'http', 'https' then klass = Net::HTTP.const_get(method.to_s.capitalize) request ||= klass.new(uri.request_uri) request.body = params.first if params request when 'file' then Mechanize::FileRequest.new uri end end |
#idle_timeout ⇒ Object
Reset connections that have not been used in this many seconds
1066 1067 1068 |
# File 'lib/mechanize/http/agent.rb', line 1066 def idle_timeout @http.idle_timeout end |
#idle_timeout=(timeout) ⇒ Object
Sets the connection idle timeout for persistent connections
1071 1072 1073 |
# File 'lib/mechanize/http/agent.rb', line 1071 def idle_timeout= timeout @http.idle_timeout = timeout end |
#inflate(compressed, window_bits = nil) ⇒ Object
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 |
# File 'lib/mechanize/http/agent.rb', line 1111 def inflate compressed, window_bits = nil inflate = Zlib::Inflate.new window_bits out_io = auto_io 'mechanize-inflate', 1024, compressed do |chunk| inflate.inflate chunk end out_io.write inflate.finish out_io ensure inflate.close end |
#log ⇒ Object
1125 1126 1127 |
# File 'lib/mechanize/http/agent.rb', line 1125 def log @context.log end |
#max_history ⇒ Object
334 335 336 |
# File 'lib/mechanize/http/agent.rb', line 334 def max_history @history.max_size end |
#max_history=(length) ⇒ Object
338 339 340 |
# File 'lib/mechanize/http/agent.rb', line 338 def max_history=(length) @history.max_size = length end |
#post_connect(uri, response, body_io) ⇒ Object
Invokes hooks added to post_connect_hooks after a response is returned and the response body is handled.
Yields the context, the uri for the request, the response and the response body.
362 363 364 365 366 367 368 369 370 |
# File 'lib/mechanize/http/agent.rb', line 362 def post_connect uri, response, body_io # :yields: agent, uri, response, body @post_connect_hooks.each do |hook| begin hook.call self, uri, response, body_io.read ensure body_io.rewind end end end |
#pre_connect(request) ⇒ Object
Invokes hooks added to pre_connect_hooks before a request is made. Yields the agent and the request that will be performed to each hook.
376 377 378 379 380 |
# File 'lib/mechanize/http/agent.rb', line 376 def pre_connect request # :yields: agent, request @pre_connect_hooks.each do |hook| hook.call self, request end end |
#private_key ⇒ Object
An OpenSSL private key or the path to a private key
1013 1014 1015 |
# File 'lib/mechanize/http/agent.rb', line 1013 def private_key @http.private_key end |
#private_key=(private_key) ⇒ Object
Sets the client’s private key
1018 1019 1020 1021 1022 1023 1024 1025 1026 |
# File 'lib/mechanize/http/agent.rb', line 1018 def private_key= private_key private_key = if OpenSSL::PKey::PKey === private_key then private_key else OpenSSL::PKey::RSA.new File.read(private_key), @pass end @http.private_key = private_key end |
#proxy_uri ⇒ Object
URI for a proxy connection
297 298 299 |
# File 'lib/mechanize/http/agent.rb', line 297 def proxy_uri @http.proxy_uri end |
#request_add_headers(request, headers = {}) ⇒ Object
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
# File 'lib/mechanize/http/agent.rb', line 471 def request_add_headers request, headers = {} @request_headers.each do |k,v| request[k] = v end headers.each do |field, value| case field when :etag then request["ETag"] = value when :if_modified_since then request["If-Modified-Since"] = value when Symbol then raise ArgumentError, "unknown header symbol #{field}" else request[field] = value end end end |
#request_auth(request, uri) ⇒ Object
488 489 490 491 492 493 494 495 496 497 498 499 500 |
# File 'lib/mechanize/http/agent.rb', line 488 def request_auth request, uri base_uri = uri + '/' schemes = @authenticate_methods[base_uri] if realm = schemes[:digest].find { |r| r.uri == base_uri } then request_auth_digest request, uri, realm, base_uri, false elsif realm = schemes[:iis_digest].find { |r| r.uri == base_uri } then request_auth_digest request, uri, realm, base_uri, true elsif realm = schemes[:basic].find { |r| r.uri == base_uri } then user, password, = @auth_store.credentials_for uri, realm.realm request.basic_auth user, password end end |
#request_auth_digest(request, uri, realm, base_uri, iis) ⇒ Object
502 503 504 505 506 507 508 509 510 511 |
# File 'lib/mechanize/http/agent.rb', line 502 def request_auth_digest request, uri, realm, base_uri, iis challenge = @digest_challenges[realm] user, password, = @auth_store.credentials_for uri, realm.realm uri.user = user uri.password = password auth = @digest_auth.auth_header uri, challenge.to_s, request.method, iis request['Authorization'] = auth end |
#request_cookies(request, uri) ⇒ Object
513 514 515 516 517 518 519 520 521 |
# File 'lib/mechanize/http/agent.rb', line 513 def request, uri return if @cookie_jar.empty? uri = @cookie_jar. uri return if .empty? request.add_field 'Cookie', .join('; ') end |
#request_host(request, uri) ⇒ Object
523 524 525 526 527 528 |
# File 'lib/mechanize/http/agent.rb', line 523 def request_host request, uri port = [80, 443].include?(uri.port.to_i) ? nil : uri.port host = uri.host request['Host'] = [host, port].compact.join ':' end |
#request_language_charset(request) ⇒ Object
530 531 532 533 |
# File 'lib/mechanize/http/agent.rb', line 530 def request_language_charset request request['accept-charset'] = 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' request['accept-language'] = 'en-us,en;q=0.5' end |
#request_log(request) ⇒ Object
Log specified headers for the request
536 537 538 539 540 541 542 543 544 |
# File 'lib/mechanize/http/agent.rb', line 536 def request_log request return unless log log.info("#{request.class}: #{request.path}") request.each_header do |k, v| log.debug("request-header: #{k} => #{v}") end end |
#request_referer(request, uri, referer) ⇒ Object
Sets a Referer header. Fragment part is removed as demanded by RFC 2616 14.36, and user information part is removed just like major browsers do.
549 550 551 552 553 554 555 556 557 558 |
# File 'lib/mechanize/http/agent.rb', line 549 def request_referer request, uri, referer return unless referer return if 'https'.casecmp(referer.scheme) == 0 and 'https'.casecmp(uri.scheme) != 0 if referer.fragment || referer.user || referer.password referer = referer.dup referer.fragment = referer.user = referer.password = nil end request['Referer'] = referer end |
#request_user_agent(request) ⇒ Object
560 561 562 |
# File 'lib/mechanize/http/agent.rb', line 560 def request_user_agent request request['User-Agent'] = @user_agent if @user_agent end |
#resolve(uri, referer = current_page) ⇒ Object
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 |
# File 'lib/mechanize/http/agent.rb', line 564 def resolve(uri, referer = current_page) referer_uri = referer && referer.uri if uri.is_a?(URI) uri = uri.dup elsif uri.nil? if referer_uri return referer_uri end raise ArgumentError, "absolute URL needed (not nil)" else url = uri.to_s.strip if url.empty? if referer_uri return referer_uri.dup.tap { |u| u.fragment = nil } end raise ArgumentError, "absolute URL needed (not #{uri.inspect})" end url.gsub!(/[^#{0.chr}-#{126.chr}]/o) { |match| if RUBY_VERSION >= "1.9.0" Mechanize::Util.uri_escape(match) else sprintf('%%%X', match.unpack($KCODE == 'UTF8' ? 'U' : 'C')[0]) end } escaped_url = Mechanize::Util.html_unescape( url.split(/((?:%[0-9A-Fa-f]{2})+|#)/).each_slice(2).map { |x, y| "#{WEBrick::HTTPUtils.escape(x)}#{y}" }.join('') ) begin uri = URI.parse(escaped_url) rescue uri = URI.parse(WEBrick::HTTPUtils.escape(escaped_url)) end end scheme = uri.relative? ? 'relative' : uri.scheme.downcase uri = @scheme_handlers[scheme].call(uri, referer) if referer_uri if uri.path.length == 0 && uri.relative? uri.path = referer_uri.path end end uri.path = '/' if uri.path.length == 0 if uri.relative? raise ArgumentError, "absolute URL needed (not #{uri})" unless referer_uri if referer.respond_to?(:bases) && referer.parser && (lbase = referer.bases.last) && lbase.uri && lbase.uri.absolute? base = lbase else base = nil end uri = referer_uri + (base ? base.uri : referer_uri) + uri # Strip initial "/.." bits from the path uri.path.sub!(/^(\/\.\.)+(?=\/)/, '') end unless ['http', 'https', 'file'].include?(uri.scheme.downcase) raise ArgumentError, "unsupported scheme: #{uri.scheme}" end uri end |
#resolve_parameters(uri, method, parameters) ⇒ Object
637 638 639 640 641 642 643 644 645 646 647 648 649 650 |
# File 'lib/mechanize/http/agent.rb', line 637 def resolve_parameters uri, method, parameters case method when :head, :get, :delete, :trace then if parameters and parameters.length > 0 uri.query ||= '' uri.query << '&' if uri.query.length > 0 uri.query << Mechanize::Util.build_query_string(parameters) end return uri, nil end return uri, parameters end |
#response_authenticate(response, page, uri, request, headers, params, referer) ⇒ Object
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 |
# File 'lib/mechanize/http/agent.rb', line 669 def response_authenticate(response, page, uri, request, headers, params, referer) www_authenticate = response['www-authenticate'] unless www_authenticate = response['www-authenticate'] then = 'WWW-Authenticate header missing in response' raise Mechanize::UnauthorizedError.new(page, nil, ) end challenges = @authenticate_parser.parse www_authenticate unless @auth_store.credentials? uri, challenges then = "no credentials found, provide some with #add_auth" raise Mechanize::UnauthorizedError.new(page, challenges, ) end if challenge = challenges.find { |c| c.scheme =~ /^Digest$/i } then realm = challenge.realm uri auth_scheme = if response['server'] =~ /Microsoft-IIS/ then :iis_digest else :digest end existing_realms = @authenticate_methods[realm.uri][auth_scheme] if existing_realms.include? realm = 'Digest authentication failed' raise Mechanize::UnauthorizedError.new(page, challeges, ) end existing_realms << realm @digest_challenges[realm] = challenge elsif challenge = challenges.find { |c| c.scheme == 'NTLM' } then existing_realms = @authenticate_methods[uri + '/'][:ntlm] if existing_realms.include?(realm) and not challenge.params then = 'NTLM authentication failed' raise Mechanize::UnauthorizedError.new(page, challenges, ) end existing_realms << realm if challenge.params then type_2 = Net::NTLM::Message.decode64 challenge.params user, password, domain = @auth_store.credentials_for uri, nil type_3 = type_2.response({ :user => user, :password => password, :domain => domain }, { :ntlmv2 => true }).encode64 headers['Authorization'] = "NTLM #{type_3}" else type_1 = Net::NTLM::Message::Type1.new.encode64 headers['Authorization'] = "NTLM #{type_1}" end elsif challenge = challenges.find { |c| c.scheme == 'Basic' } then realm = challenge.realm uri existing_realms = @authenticate_methods[realm.uri][:basic] if existing_realms.include? realm then = 'Basic authentication failed' raise Mechanize::UnauthorizedError.new(page, challenges, ) end existing_realms << realm else = 'unsupported authentication scheme' raise Mechanize::UnauthorizedError.new(page, challenges, ) end fetch uri, request.method.downcase.to_sym, headers, params, referer end |
#response_content_encoding(response, body_io) ⇒ Object
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 |
# File 'lib/mechanize/http/agent.rb', line 746 def response_content_encoding response, body_io length = response.content_length || case body_io when Tempfile, IO then body_io.stat.size else body_io.length end return body_io if length.zero? out_io = case response['Content-Encoding'] when nil, 'none', '7bit' then body_io when 'deflate' then content_encoding_inflate body_io when 'gzip', 'x-gzip' then content_encoding_gunzip body_io else raise Mechanize::Error, "unsupported content-encoding: #{response['Content-Encoding']}" end out_io.flush out_io.rewind out_io rescue Zlib::Error => e = "error handling content-encoding #{response['Content-Encoding']}:" << " #{e.} (#{e.class})" raise Mechanize::Error, ensure begin if Tempfile === body_io and (StringIO === out_io or out_io.path != body_io.path) then body_io.close! end rescue IOError # HACK ruby 1.8 raises IOError when closing the stream end end |
#response_cookies(response, uri, page) ⇒ Object
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 |
# File 'lib/mechanize/http/agent.rb', line 788 def response, uri, page if Mechanize::Page === page and page.body =~ /Set-Cookie/n page.search('//head/meta[@http-equiv="Set-Cookie"]').each do || (uri, ['content']) end end = response.get_fields 'Set-Cookie' return unless .each do || (uri, ) end end |
#response_follow_meta_refresh(response, uri, page, redirects) ⇒ Object
815 816 817 818 819 820 821 822 823 824 825 826 827 |
# File 'lib/mechanize/http/agent.rb', line 815 def response, uri, page, redirects delay, new_url = (response, uri, page) return nil unless delay new_url = new_url ? resolve(new_url, page) : uri raise Mechanize::RedirectLimitReachedError.new(page, redirects) if redirects + 1 > @redirection_limit sleep delay @history.push(page, page.uri) fetch new_url, :get, {}, [], Mechanize::Page.new, redirects end |
#response_log(response) ⇒ Object
829 830 831 832 833 834 835 836 837 838 |
# File 'lib/mechanize/http/agent.rb', line 829 def response_log response return unless log log.info("status: #{response.class} #{response.http_version} " \ "#{response.code} #{response.}") response.each_header do |k, v| log.debug("response-header: #{k} => #{v}") end end |
#response_parse(response, body_io, uri) ⇒ Object
840 841 842 |
# File 'lib/mechanize/http/agent.rb', line 840 def response_parse response, body_io, uri @context.parse uri, response, body_io end |
#response_read(response, request, uri) ⇒ Object
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 |
# File 'lib/mechanize/http/agent.rb', line 844 def response_read response, request, uri content_length = response.content_length if use_tempfile? content_length then body_io = Tempfile.new 'mechanize-raw' body_io.unlink body_io.binmode if defined? body_io.binmode else body_io = StringIO.new end body_io.set_encoding Encoding::BINARY if body_io.respond_to? :set_encoding total = 0 begin response.read_body { |part| total += part.length if StringIO === body_io and use_tempfile? total then new_io = Tempfile.new 'mechanize-raw' new_io.unlink new_io.binmode new_io.write body_io.string body_io = new_io end body_io.write(part) log.debug("Read #{part.length} bytes (#{total} total)") if log } rescue Net::HTTP::Persistent::Error => e body_io.rewind raise Mechanize::ResponseReadError.new(e, response, body_io, uri, @context) end body_io.flush body_io.rewind raise Mechanize::ResponseCodeError.new(response, uri) if Net::HTTPUnknownResponse === response content_length = response.content_length unless Net::HTTP::Head === request or Net::HTTPRedirection === response then raise EOFError, "Content-Length (#{content_length}) does not match " \ "response body length (#{body_io.length})" if content_length and content_length != body_io.length end body_io end |
#response_redirect(response, method, page, redirects, referer = current_page) ⇒ Object
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 |
# File 'lib/mechanize/http/agent.rb', line 898 def response_redirect response, method, page, redirects, referer = current_page case @redirect_ok when true, :all # shortcut when false, nil return page when :permanent return page unless Net::HTTPMovedPermanently === response end log.info("follow redirect to: #{response['Location']}") if log raise Mechanize::RedirectLimitReachedError.new(page, redirects) if redirects + 1 > @redirection_limit redirect_method = method == :head ? :head : :get @history.push(page, page.uri) new_uri = resolve response['Location'].to_s, page fetch new_uri, redirect_method, {}, [], referer, redirects + 1 end |
#retry_change_requests ⇒ Object
Retry non-idempotent requests?
302 303 304 |
# File 'lib/mechanize/http/agent.rb', line 302 def retry_change_requests @http.retry_change_requests end |
#retry_change_requests=(retri) ⇒ Object
Retry non-idempotent requests
308 309 310 |
# File 'lib/mechanize/http/agent.rb', line 308 def retry_change_requests= retri @http.retry_change_requests = retri end |
#robots_allowed?(uri) ⇒ Boolean
Tests if this agent is allowed to access url, consulting the site’s robots.txt.
940 941 942 943 944 |
# File 'lib/mechanize/http/agent.rb', line 940 def robots_allowed? uri return true if uri.request_uri == '/robots.txt' webrobots.allowed? uri end |
#robots_disallowed?(url) ⇒ Boolean
Opposite of robots_allowed?
948 949 950 |
# File 'lib/mechanize/http/agent.rb', line 948 def robots_disallowed? url !robots_allowed? url end |
#robots_error(url) ⇒ Object
Returns an error object if there is an error in fetching or parsing robots.txt of the site url.
954 955 956 |
# File 'lib/mechanize/http/agent.rb', line 954 def robots_error(url) webrobots.error(url) end |
#robots_error!(url) ⇒ Object
Raises the error if there is an error in fetching or parsing robots.txt of the site url.
960 961 962 |
# File 'lib/mechanize/http/agent.rb', line 960 def robots_error!(url) webrobots.error!(url) end |
#robots_reset(url) ⇒ Object
Removes robots.txt cache for the site url.
965 966 967 |
# File 'lib/mechanize/http/agent.rb', line 965 def robots_reset(url) webrobots.reset(url) end |
#save_cookies(uri, set_cookie) ⇒ Object
804 805 806 807 808 809 810 811 812 813 |
# File 'lib/mechanize/http/agent.rb', line 804 def (uri, ) log = log() # reduce method calls Mechanize::Cookie.parse(uri, , log) { |c| if @cookie_jar.add(uri, c) log.debug("saved cookie: #{c}") if log else log.debug("rejected cookie: #{c}") if log end } end |
#set_proxy(addr, port, user = nil, pass = nil) ⇒ Object
Sets the proxy address, port, user, and password addr should be a host, with no “http://”, port may be a port number, service name or port number string.
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 |
# File 'lib/mechanize/http/agent.rb', line 1134 def set_proxy addr, port, user = nil, pass = nil unless addr and port then @http.proxy = nil return end unless Integer === port then begin port = Socket.getservbyname port rescue SocketError begin port = Integer port rescue ArgumentError raise ArgumentError, "invalid value for port: #{port.inspect}" end end end proxy_uri = URI "http://#{addr}" proxy_uri.port = port proxy_uri.user = user if user proxy_uri.password = pass if pass @http.proxy = proxy_uri end |
#ssl_version ⇒ Object
SSL version to use
1029 1030 1031 |
# File 'lib/mechanize/http/agent.rb', line 1029 def ssl_version @http.ssl_version end |
#ssl_version=(ssl_version) ⇒ Object
Sets the SSL version to use
1034 1035 1036 |
# File 'lib/mechanize/http/agent.rb', line 1034 def ssl_version= ssl_version @http.ssl_version = ssl_version end |
#use_tempfile?(size) ⇒ Boolean
1161 1162 1163 1164 1165 1166 |
# File 'lib/mechanize/http/agent.rb', line 1161 def use_tempfile? size return false unless @max_file_buffer return false unless size size >= @max_file_buffer end |
#verify_callback ⇒ Object
A callback for additional certificate verification. See OpenSSL::SSL::SSLContext#verify_callback
The callback can be used for debugging or to ignore errors by always returning true. Specifying nil uses the default method that was valid when the SSLContext was created
1044 1045 1046 |
# File 'lib/mechanize/http/agent.rb', line 1044 def verify_callback @http.verify_callback end |
#verify_callback=(verify_callback) ⇒ Object
Sets the certificate verify callback
1049 1050 1051 |
# File 'lib/mechanize/http/agent.rb', line 1049 def verify_callback= verify_callback @http.verify_callback = verify_callback end |
#verify_mode ⇒ Object
How to verify SSL connections. Defaults to VERIFY_PEER
1054 1055 1056 |
# File 'lib/mechanize/http/agent.rb', line 1054 def verify_mode @http.verify_mode end |
#verify_mode=(verify_mode) ⇒ Object
Sets the mode for verifying SSL connections
1059 1060 1061 |
# File 'lib/mechanize/http/agent.rb', line 1059 def verify_mode= verify_mode @http.verify_mode = verify_mode end |
#visited_page(url) ⇒ Object
Returns a visited page for the url passed in, otherwise nil
343 344 345 |
# File 'lib/mechanize/http/agent.rb', line 343 def visited_page url @history.visited_page resolve url end |
#webrobots ⇒ Object
969 970 971 |
# File 'lib/mechanize/http/agent.rb', line 969 def webrobots @webrobots ||= WebRobots.new(@user_agent, :http_get => method(:get_robots)) end |