Class: HTTPClient
- Inherits:
-
Object
- Object
- HTTPClient
- Includes:
- Util
- Defined in:
- lib/httpclient.rb,
lib/httpclient/auth.rb,
lib/httpclient/util.rb,
lib/httpclient/session.rb,
lib/httpclient/version.rb,
lib/httpclient/lru_cache.rb,
lib/httpclient/connection.rb,
lib/httpclient/ssl_config.rb,
lib/httpclient/include_client.rb
Overview
It is useful to re-use a HTTPClient instance for multiple requests, to re-use HTTP 1.1 persistent connections.
To do that, you sometimes want to store an HTTPClient instance in a global/ class variable location, so it can be accessed and re-used.
This mix-in makes it easy to create class-level access to one or more HTTPClient instances. The HTTPClient instances are lazily initialized on first use (to, for instance, avoid interfering with WebMock/VCR), and are initialized in a thread-safe manner. Note that a HTTPClient, once initialized, is safe for use in multiple threads.
Note that you ‘extend` HTTPClient::IncludeClient, not `include.
require 'httpclient/include_client'
class Widget
extend HTTPClient::IncludeClient
include_http_client
# and/or, specify more stuff
include_http_client('http://myproxy:8080', :method_name => :my_client) do |client|
# any init you want
client.set_cookie_store nil
client.
end
end
That creates two HTTPClient instances available at the class level. The first will be available from Widget.http_client (default method name for ‘include_http_client`), with default initialization.
The second will be available at Widget.my_client, with the init arguments provided, further initialized by the block provided.
In addition to a class-level method, for convenience instance-level methods are also provided. Widget.http_client is identical to Widget.new.http_client
Direct Known Subclasses
Defined Under Namespace
Modules: DebugSocket, IncludeClient, SocketWrap, Util Classes: AuthFilterBase, BadResponseError, BasicAuth, ConfigurationError, ConnectTimeoutError, Connection, DigestAuth, KeepAliveDisconnected, LRUCache, LoopBackSocket, NegotiateAuth, OAuth, ProxyAuth, ProxyBasicAuth, ProxyDigestAuth, ReceiveTimeoutError, RetryableResponse, SSLConfig, SSLSocketWrap, SSPINegotiateAuth, SendTimeoutError, Session, SessionManager, Site, TimeoutError, WWWAuth
Constant Summary collapse
- RUBY_VERSION_STRING =
"ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
- LIB_NAME =
"(#{VERSION}, #{RUBY_VERSION_STRING})"
- PROPFIND_DEFAULT_EXTHEADER =
Default header for PROPFIND request.
{ 'Depth' => '0' }
- DEFAULT_AGENT_NAME =
Default User-Agent header
"HTTPClient #{VERSION}"
- VERSION =
'3.2.2'
- @@dns_cache =
HTTPClient::LRUCache.new(ttl: 20.minutes, soft_ttl: 10.minute, retry_delay: 5.minutes)
Instance Attribute Summary collapse
-
#cookie_manager ⇒ Object
- WebAgent::CookieManager
-
Cookies configurator.
-
#follow_redirect_count ⇒ Object
How many times get_content and post_content follows HTTP redirect.
-
#proxy_auth ⇒ Object
readonly
- HTTPClient::ProxyAuth
-
Proxy authentication handler.
-
#request_filter ⇒ Object
readonly
An array of request filter which can trap HTTP request/response.
-
#ssl_config ⇒ Object
readonly
- HTTPClient::SSLConfig
-
SSL configurator.
-
#test_loopback_response ⇒ Object
readonly
An array of response HTTP message body String which is used for loop-back test.
-
#www_auth ⇒ Object
readonly
- HTTPClient::WWWAuth
-
WWW authentication handler.
Instance Method Summary collapse
-
#cookies ⇒ Object
Returns stored cookies.
-
#debug_dev ⇒ Object
Returns debug device if exists.
-
#debug_dev=(dev) ⇒ Object
Sets debug device.
-
#default_redirect_uri_callback(uri, res) ⇒ Object
A default method for redirect uri callback.
-
#delete(uri, *args, &block) ⇒ Object
Sends DELETE request to the specified URL.
-
#delete_async(uri, *args) ⇒ Object
Sends DELETE request in async style.
- #download_file(uri, file, *args) ⇒ Object
-
#get(uri, *args, &block) ⇒ Object
Sends GET request to the specified URL.
-
#get_async(uri, *args) ⇒ Object
Sends GET request in async style.
-
#get_content(uri, *args, &block) ⇒ Object
Retrieves a web resource.
-
#head(uri, *args) ⇒ Object
Sends HEAD request to the specified URL.
-
#head_async(uri, *args) ⇒ Object
Sends HEAD request in async style.
-
#initialize(*args) ⇒ HTTPClient
constructor
Creates a HTTPClient instance which manages sessions, cookies, etc.
-
#keep_webmock_compat ⇒ Object
webmock 1.6.2 depends on HTTP::Message#body.content to work.
-
#no_proxy ⇒ Object
Returns NO_PROXY setting String if given.
-
#no_proxy=(no_proxy) ⇒ Object
Sets NO_PROXY setting String.
-
#options(uri, *args, &block) ⇒ Object
Sends OPTIONS request to the specified URL.
-
#options_async(uri, *args) ⇒ Object
Sends OPTIONS request in async style.
- #own_methods ⇒ Object
-
#patch(uri, *args, &block) ⇒ Object
Sends PATCH request to the specified URL.
-
#patch_async(uri, *args) ⇒ Object
Sends PATCH request in async style.
-
#post(uri, *args, &block) ⇒ Object
Sends POST request to the specified URL.
-
#post_async(uri, *args) ⇒ Object
Sends POST request in async style.
-
#post_content(uri, *args, &block) ⇒ Object
Posts a content.
-
#propfind(uri, *args, &block) ⇒ Object
Sends PROPFIND request to the specified URL.
-
#propfind_async(uri, *args) ⇒ Object
Sends PROPFIND request in async style.
-
#proppatch(uri, *args, &block) ⇒ Object
Sends PROPPATCH request to the specified URL.
-
#proppatch_async(uri, *args) ⇒ Object
Sends PROPPATCH request in async style.
-
#proxy ⇒ Object
Returns URI object of HTTP proxy if exists.
-
#proxy=(proxy) ⇒ Object
Sets HTTP proxy used for HTTP connection.
-
#put(uri, *args, &block) ⇒ Object
Sends PUT request to the specified URL.
-
#put_async(uri, *args) ⇒ Object
Sends PUT request in async style.
-
#redirect_uri_callback=(redirect_uri_callback) ⇒ Object
Sets callback proc when HTTP redirect status is returned for get_content and post_content.
-
#request(method, uri, *args, &block) ⇒ Object
Sends a request to the specified URL.
-
#request_async(method, uri, query = nil, body = nil, header = {}) ⇒ Object
Sends a request in async style.
-
#reset(uri) ⇒ Object
Resets internal session for the given URL.
-
#reset_all ⇒ Object
Resets all of internal sessions.
-
#save_cookie_store ⇒ Object
Try to save Cookies to the file specified in set_cookie_store.
-
#set_auth(domain, user, passwd) ⇒ Object
Sets credential for Web server authentication.
-
#set_basic_auth(domain, user, passwd) ⇒ Object
Deprecated.
-
#set_cookie_store(filename) ⇒ Object
Sets the filename where non-volatile Cookies be saved by calling save_cookie_store.
-
#set_proxy_auth(user, passwd) ⇒ Object
Sets credential for Proxy authentication.
-
#strict_redirect_uri_callback(uri, res) ⇒ Object
A method for redirect uri callback.
-
#trace(uri, *args, &block) ⇒ Object
Sends TRACE request to the specified URL.
-
#trace_async(uri, *args) ⇒ Object
Sends TRACE request in async style.
Methods included from Util
#argument_to_hash, get_buf, hash_find_value, #http?, #https?, #keyword_argument, uri_dirname, uri_part_of, urify
Constructor Details
#initialize(*args) ⇒ HTTPClient
Creates a HTTPClient instance which manages sessions, cookies, etc.
HTTPClient.new takes 3 optional arguments for proxy url string, User-Agent String and From header String. User-Agent and From are embedded in HTTP request Header if given. No User-Agent and From header added without setting it explicitly.
proxy = 'http://myproxy:8080'
agent_name = 'MyAgent/0.1'
from = '[email protected]'
HTTPClient.new(proxy, agent_name, from)
You can use a keyword argument style Hash. Keys are :proxy, :agent_name and :from.
HTTPClient.new(:agent_name => 'MyAgent/0.1')
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'lib/httpclient.rb', line 391 def initialize(*args) proxy, agent_name, from = keyword_argument(args, :proxy, :agent_name, :from) @proxy = nil # assigned later. @no_proxy = nil @no_proxy_regexps = [] @www_auth = WWWAuth.new @proxy_auth = ProxyAuth.new @request_filter = [@proxy_auth, @www_auth] @debug_dev = nil @redirect_uri_callback = method(:default_redirect_uri_callback) @test_loopback_response = [] @session_manager = SessionManager.new(self) @session_manager.agent_name = agent_name || DEFAULT_AGENT_NAME @session_manager.from = from @session_manager.ssl_config = @ssl_config = SSLConfig.new(self) @cookie_manager = WebAgent::CookieManager.new @follow_redirect_count = 10 load_environment self.proxy = proxy if proxy keep_webmock_compat end |
Instance Attribute Details
#cookie_manager ⇒ Object
- WebAgent::CookieManager
-
Cookies configurator.
324 325 326 |
# File 'lib/httpclient.rb', line 324 def @cookie_manager end |
#follow_redirect_count ⇒ Object
How many times get_content and post_content follows HTTP redirect. 10 by default.
338 339 340 |
# File 'lib/httpclient.rb', line 338 def follow_redirect_count @follow_redirect_count end |
#proxy_auth ⇒ Object (readonly)
- HTTPClient::ProxyAuth
-
Proxy authentication handler.
333 334 335 |
# File 'lib/httpclient.rb', line 333 def proxy_auth @proxy_auth end |
#request_filter ⇒ Object (readonly)
An array of request filter which can trap HTTP request/response. See HTTPClient::WWWAuth to see how to use it.
331 332 333 |
# File 'lib/httpclient.rb', line 331 def request_filter @request_filter end |
#ssl_config ⇒ Object (readonly)
- HTTPClient::SSLConfig
-
SSL configurator.
322 323 324 |
# File 'lib/httpclient.rb', line 322 def ssl_config @ssl_config end |
#test_loopback_response ⇒ Object (readonly)
An array of response HTTP message body String which is used for loop-back test. See test/* to see how to use it. If you want to do loop-back test of HTTP header, use test_loopback_http_response instead.
328 329 330 |
# File 'lib/httpclient.rb', line 328 def test_loopback_response @test_loopback_response end |
#www_auth ⇒ Object (readonly)
- HTTPClient::WWWAuth
-
WWW authentication handler.
335 336 337 |
# File 'lib/httpclient.rb', line 335 def www_auth @www_auth end |
Instance Method Details
#cookies ⇒ Object
Returns stored cookies.
565 566 567 568 569 |
# File 'lib/httpclient.rb', line 565 def if @cookie_manager @cookie_manager. end end |
#debug_dev ⇒ Object
Returns debug device if exists. See debug_dev=.
429 430 431 |
# File 'lib/httpclient.rb', line 429 def debug_dev @debug_dev end |
#debug_dev=(dev) ⇒ Object
Sets debug device. Once debug device is set, all HTTP requests and responses are dumped to given device. dev must respond to << for dump.
Calling this method resets all existing sessions.
437 438 439 440 441 |
# File 'lib/httpclient.rb', line 437 def debug_dev=(dev) @debug_dev = dev reset_all @session_manager.debug_dev = dev end |
#default_redirect_uri_callback(uri, res) ⇒ Object
A default method for redirect uri callback. This method is used by HTTPClient instance by default. This callback allows relative redirect such as
Location: ../foo/
in HTTP header.
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 |
# File 'lib/httpclient.rb', line 668 def default_redirect_uri_callback(uri, res) newuri = urify(res.header['location'][0]) if !http?(newuri) && !https?(newuri) newuri = uri + newuri warn("could be a relative URI in location header which is not recommended") warn("'The field value consists of a single absolute URI' in HTTP spec") end if https?(uri) && !https?(newuri) #raise BadResponseError.new("redirecting to non-https resource") # allow redirect to non-https but warn warn("redirecting to non-https resource") end puts "redirect to: #{newuri}" if $DEBUG newuri end |
#delete(uri, *args, &block) ⇒ Object
Sends DELETE request to the specified URL. See request for arguments.
712 713 714 |
# File 'lib/httpclient.rb', line 712 def delete(uri, *args, &block) request(:delete, uri, argument_to_hash(args, :body, :header), &block) end |
#delete_async(uri, *args) ⇒ Object
Sends DELETE request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
847 848 849 850 |
# File 'lib/httpclient.rb', line 847 def delete_async(uri, *args) header = keyword_argument(args, :header) request_async(:delete, uri, nil, nil, header || {}) end |
#download_file(uri, file, *args) ⇒ Object
736 737 738 739 740 741 742 743 |
# File 'lib/httpclient.rb', line 736 def download_file(uri, file, *args) io = File.open(file, 'a+b') request(:get, uri, argument_to_hash(args, :query, :header, :follow_redirect)) do |s| io.write(s) end io.flush io end |
#get(uri, *args, &block) ⇒ Object
Sends GET request to the specified URL. See request for arguments.
690 691 692 |
# File 'lib/httpclient.rb', line 690 def get(uri, *args, &block) request(:get, uri, argument_to_hash(args, :query, :header, :follow_redirect), &block) end |
#get_async(uri, *args) ⇒ Object
Sends GET request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
819 820 821 822 |
# File 'lib/httpclient.rb', line 819 def get_async(uri, *args) query, header = keyword_argument(args, :query, :header) request_async(:get, uri, query, nil, header || {}) end |
#get_content(uri, *args, &block) ⇒ Object
Retrieves a web resource.
- uri
-
a String or an URI object which represents an URL of web resource.
- query
-
a Hash or an Array of query part of URL. e.g. { “a” => “b” } => ‘host/part?a=b’. Give an array to pass multiple value like
- [“a”, “b”], [“a”, “c”]
-
> ‘host/part?a=b&a=c’.
- header
-
a Hash or an Array of extra headers. e.g. { ‘Accept’ => ‘text/html’ } or [[‘Accept’, ‘image/jpeg’], [‘Accept’, ‘image/png’]].
- &block
-
Give a block to get chunked message-body of response like get_content(uri) { |chunked_body| … }. Size of each chunk may not be the same.
get_content follows HTTP redirect status (see HTTP::Status.redirect?) internally and try to retrieve content from redirected URL. See redirect_uri_callback= how HTTP redirection is handled.
If you need to get full HTTP response including HTTP status and headers, use get method. get returns HTTP::Message as a response and you need to follow HTTP redirect by yourself if you need.
604 605 606 607 |
# File 'lib/httpclient.rb', line 604 def get_content(uri, *args, &block) query, header = keyword_argument(args, :query, :header) success_content(follow_redirect(:get, uri, query, nil, header || {}, &block)) end |
#head(uri, *args) ⇒ Object
Sends HEAD request to the specified URL. See request for arguments.
685 686 687 |
# File 'lib/httpclient.rb', line 685 def head(uri, *args) request(:head, uri, argument_to_hash(args, :query, :header, :follow_redirect)) end |
#head_async(uri, *args) ⇒ Object
Sends HEAD request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
812 813 814 815 |
# File 'lib/httpclient.rb', line 812 def head_async(uri, *args) query, header = keyword_argument(args, :query, :header) request_async(:head, uri, query, nil, header || {}) end |
#keep_webmock_compat ⇒ Object
webmock 1.6.2 depends on HTTP::Message#body.content to work. let’s keep it work iif webmock is loaded for a while.
415 416 417 418 419 420 421 422 423 424 425 426 |
# File 'lib/httpclient.rb', line 415 def keep_webmock_compat if respond_to?(:do_get_block_with_webmock) ::HTTP::Message.module_eval do def body def (o = self.content).content self end o end end end end |
#no_proxy ⇒ Object
Returns NO_PROXY setting String if given.
479 480 481 |
# File 'lib/httpclient.rb', line 479 def no_proxy @no_proxy end |
#no_proxy=(no_proxy) ⇒ Object
Sets NO_PROXY setting String. no_proxy must be a comma separated String. Each entry must be ‘host’ or ‘host:port’ such as; HTTPClient#no_proxy = ‘example.com,example.co.jp:443’
‘localhost’ is treated as a no_proxy site regardless of explicitly listed. HTTPClient checks given URI objects before accessing it. ‘host’ is tail string match. No IP-addr conversion.
You can use environment variable ‘no_proxy’ or ‘NO_PROXY’ for it.
Calling this method resets all existing sessions.
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 |
# File 'lib/httpclient.rb', line 494 def no_proxy=(no_proxy) @no_proxy = no_proxy @no_proxy_regexps.clear if @no_proxy @no_proxy.scan(/([^:,]+)(?::(\d+))?/) do |host, port| if host[0] == ?. regexp = /#{Regexp.quote(host)}\z/i else regexp = /(\A|\.)#{Regexp.quote(host)}\z/i end @no_proxy_regexps << [regexp, port] end end reset_all end |
#options(uri, *args, &block) ⇒ Object
Sends OPTIONS request to the specified URL. See request for arguments.
717 718 719 |
# File 'lib/httpclient.rb', line 717 def (uri, *args, &block) request(:options, uri, argument_to_hash(args, :header), &block) end |
#options_async(uri, *args) ⇒ Object
Sends OPTIONS request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
854 855 856 857 |
# File 'lib/httpclient.rb', line 854 def (uri, *args) header = keyword_argument(args, :header) request_async(:options, uri, nil, nil, header || {}) end |
#own_methods ⇒ Object
240 241 242 |
# File 'lib/httpclient.rb', line 240 def own_methods (methods - (self.class.ancestors - [self.class]).collect { |k| k.instance_methods }.flatten).sort end |
#patch(uri, *args, &block) ⇒ Object
Sends PATCH request to the specified URL. See request for arguments.
707 708 709 |
# File 'lib/httpclient.rb', line 707 def patch(uri, *args, &block) request(:patch, uri, argument_to_hash(args, :body, :header), &block) end |
#patch_async(uri, *args) ⇒ Object
Sends PATCH request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
840 841 842 843 |
# File 'lib/httpclient.rb', line 840 def patch_async(uri, *args) body, header = keyword_argument(args, :body, :header) request_async(:patch, uri, nil, body || '', header || {}) end |
#post(uri, *args, &block) ⇒ Object
Sends POST request to the specified URL. See request for arguments. You should not depend on :follow_redirect => true for POST method. It sends the same POST method to the new location which is prohibited in HTTP spec.
697 698 699 |
# File 'lib/httpclient.rb', line 697 def post(uri, *args, &block) request(:post, uri, argument_to_hash(args, :body, :header, :follow_redirect), &block) end |
#post_async(uri, *args) ⇒ Object
Sends POST request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
826 827 828 829 |
# File 'lib/httpclient.rb', line 826 def post_async(uri, *args) body, header = keyword_argument(args, :body, :header) request_async(:post, uri, nil, body || '', header || {}) end |
#post_content(uri, *args, &block) ⇒ Object
Posts a content.
- uri
-
a String or an URI object which represents an URL of web resource.
- body
-
a Hash or an Array of body part. e.g.
{ "a" => "b" } => 'a=b'
Give an array to pass multiple value like
[["a", "b"], ["a", "c"]] => 'a=b&a=c'
When you pass a File as a value, it will be posted as a multipart/form-data. e.g.
{ 'upload' => file }
You can also send custom multipart by passing an array of hashes. Each part must have a :content attribute which can be a file, all other keys will become headers.
[{ 'Content-Type' => 'text/plain', :content => "some text" }, { 'Content-Type' => 'video/mp4', :content => File.new('video.mp4') }] => <Two parts with custom Content-Type header>
- header
-
a Hash or an Array of extra headers. e.g.
{ 'Accept' => 'text/html' }
or
[['Accept', 'image/jpeg'], ['Accept', 'image/png']].
- &block
-
Give a block to get chunked message-body of response like
post_content(uri) { |chunked_body| ... }.
Size of each chunk may not be the same.
post_content follows HTTP redirect status (see HTTP::Status.redirect?) internally and try to post the content to redirected URL. See redirect_uri_callback= how HTTP redirection is handled. Bear in mind that you should not depend on post_content because it sends the same POST method to the new location which is prohibited in HTTP spec.
If you need to get full HTTP response including HTTP status and headers, use post method.
641 642 643 644 |
# File 'lib/httpclient.rb', line 641 def post_content(uri, *args, &block) body, header = keyword_argument(args, :body, :header) success_content(follow_redirect(:post, uri, nil, body, header || {}, &block)) end |
#propfind(uri, *args, &block) ⇒ Object
Sends PROPFIND request to the specified URL. See request for arguments.
722 723 724 |
# File 'lib/httpclient.rb', line 722 def propfind(uri, *args, &block) request(:propfind, uri, argument_to_hash(args, :header), &block) end |
#propfind_async(uri, *args) ⇒ Object
Sends PROPFIND request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
861 862 863 864 |
# File 'lib/httpclient.rb', line 861 def propfind_async(uri, *args) header = keyword_argument(args, :header) request_async(:propfind, uri, nil, nil, header || PROPFIND_DEFAULT_EXTHEADER) end |
#proppatch(uri, *args, &block) ⇒ Object
Sends PROPPATCH request to the specified URL. See request for arguments.
727 728 729 |
# File 'lib/httpclient.rb', line 727 def proppatch(uri, *args, &block) request(:proppatch, uri, argument_to_hash(args, :body, :header), &block) end |
#proppatch_async(uri, *args) ⇒ Object
Sends PROPPATCH request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
868 869 870 871 |
# File 'lib/httpclient.rb', line 868 def proppatch_async(uri, *args) body, header = keyword_argument(args, :body, :header) request_async(:proppatch, uri, nil, body, header || {}) end |
#proxy ⇒ Object
Returns URI object of HTTP proxy if exists.
444 445 446 |
# File 'lib/httpclient.rb', line 444 def proxy @proxy end |
#proxy=(proxy) ⇒ Object
Sets HTTP proxy used for HTTP connection. Given proxy can be an URI, a String or nil. You can set user/password for proxy authentication like HTTPClient#proxy = ‘user:passwd@myproxy:8080’
You can use environment variable ‘http_proxy’ or ‘HTTP_PROXY’ for it. You need to use ‘cgi_http_proxy’ or ‘CGI_HTTP_PROXY’ instead if you run HTTPClient from CGI environment from security reason. (HTTPClient checks ‘REQUEST_METHOD’ environment variable whether it’s CGI or not)
Calling this method resets all existing sessions.
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 |
# File 'lib/httpclient.rb', line 458 def proxy=(proxy) if proxy.nil? || proxy.to_s.empty? @proxy = nil @proxy_auth.reset_challenge else @proxy = urify(proxy) if @proxy.scheme == nil or @proxy.scheme.downcase != 'http' or @proxy.host == nil or @proxy.port == nil raise ArgumentError.new("unsupported proxy #{proxy}") end @proxy_auth.reset_challenge if @proxy.user || @proxy.password @proxy_auth.set_auth(@proxy.user, @proxy.password) end end reset_all @session_manager.proxy = @proxy @proxy end |
#put(uri, *args, &block) ⇒ Object
Sends PUT request to the specified URL. See request for arguments.
702 703 704 |
# File 'lib/httpclient.rb', line 702 def put(uri, *args, &block) request(:put, uri, argument_to_hash(args, :body, :header), &block) end |
#put_async(uri, *args) ⇒ Object
Sends PUT request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
833 834 835 836 |
# File 'lib/httpclient.rb', line 833 def put_async(uri, *args) body, header = keyword_argument(args, :body, :header) request_async(:put, uri, nil, body || '', header || {}) end |
#redirect_uri_callback=(redirect_uri_callback) ⇒ Object
Sets callback proc when HTTP redirect status is returned for get_content and post_content. default_redirect_uri_callback is used by default.
If you need strict implementation which does not allow relative URI redirection, set strict_redirect_uri_callback instead.
clnt.redirect_uri_callback = clnt.method(:strict_redirect_uri_callback)
579 580 581 |
# File 'lib/httpclient.rb', line 579 def redirect_uri_callback=(redirect_uri_callback) @redirect_uri_callback = redirect_uri_callback end |
#request(method, uri, *args, &block) ⇒ Object
Sends a request to the specified URL.
- method
-
HTTP method to be sent. method.to_s.upcase is used.
- uri
-
a String or an URI object which represents an URL of web resource.
- query
-
a Hash or an Array of query part of URL. e.g. { “a” => “b” } => ‘host/part?a=b’ Give an array to pass multiple value like
- [“a”, “b”], [“a”, “c”]
-
> ‘host/part?a=b&a=c’
- body
-
a Hash or an Array of body part. e.g.
{ "a" => "b" } => 'a=b'
Give an array to pass multiple value like
[["a", "b"], ["a", "c"]] => 'a=b&a=c'.
When the given method is ‘POST’ and the given body contains a file as a value, it will be posted as a multipart/form-data. e.g.
{ 'upload' => file }
You can also send custom multipart by passing an array of hashes. Each part must have a :content attribute which can be a file, all other keys will become headers.
[{ 'Content-Type' => 'text/plain', :content => "some text" }, { 'Content-Type' => 'video/mp4', :content => File.new('video.mp4') }] => <Two parts with custom Content-Type header>
See HTTP::Message.file? for actual condition of ‘a file’.
- header
-
a Hash or an Array of extra headers. e.g. { ‘Accept’ => ‘text/html’ } or [[‘Accept’, ‘image/jpeg’], [‘Accept’, ‘image/png’]].
- &block
-
Give a block to get chunked message-body of response like get(uri) { |chunked_body| … }. Size of each chunk may not be the same.
You can also pass a String as a body. HTTPClient just sends a String as a HTTP request message body.
When you pass an IO as a body, HTTPClient sends it as a HTTP request with chunked encoding (Transfer-Encoding: chunked in HTTP header) if IO does not respond to :read. Bear in mind that some server application does not support chunked request. At least cgi.rb does not support it.
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 |
# File 'lib/httpclient.rb', line 783 def request(method, uri, *args, &block) query, body, header, is_follow_redirect, filter_block = keyword_argument(args, :query, :body, :header, :follow_redirect, :filter_block) if [:post, :put, :patch].include?(method) body ||= '' end if method == :propfind header ||= PROPFIND_DEFAULT_EXTHEADER else header ||= {} end uri = urify(uri) if block if filter_block === false filtered_block = block else filtered_block = proc { |res, str| block.call(str) } end end if is_follow_redirect follow_redirect(method, uri, query, body, header, filter_block, &block) else do_request(method, uri, query, body, header, &filtered_block) end end |
#request_async(method, uri, query = nil, body = nil, header = {}) ⇒ Object
Sends a request in async style. request method creates new Thread for HTTP connection and returns a HTTPClient::Connection instance immediately.
Arguments definition is the same as request.
884 885 886 887 |
# File 'lib/httpclient.rb', line 884 def request_async(method, uri, query = nil, body = nil, header = {}) uri = urify(uri) do_request_async(method, uri, query, body, header) end |
#reset(uri) ⇒ Object
Resets internal session for the given URL. Keep-alive connection for the site (host-port pair) is disconnected if exists.
891 892 893 894 |
# File 'lib/httpclient.rb', line 891 def reset(uri) uri = urify(uri) @session_manager.reset(uri) end |
#reset_all ⇒ Object
Resets all of internal sessions. Keep-alive connections are disconnected.
897 898 899 |
# File 'lib/httpclient.rb', line 897 def reset_all @session_manager.reset_all end |
#save_cookie_store ⇒ Object
Try to save Cookies to the file specified in set_cookie_store. Unexpected error will be raised if you don’t call set_cookie_store first. (interface mismatch between WebAgent::CookieManager implementation)
560 561 562 |
# File 'lib/httpclient.rb', line 560 def @cookie_manager. end |
#set_auth(domain, user, passwd) ⇒ Object
Sets credential for Web server authentication.
- domain
-
a String or an URI to specify where HTTPClient should use this
credential. If you set uri to nil, HTTPClient uses this credential
wherever a server requires it.
- user
-
username String.
- passwd
-
password String.
You can set multiple credentials for each uri.
clnt.set_auth('http://www.example.com/foo/', 'foo_user', 'passwd')
clnt.set_auth('http://www.example.com/bar/', 'bar_user', 'passwd')
Calling this method resets all existing sessions.
523 524 525 526 527 |
# File 'lib/httpclient.rb', line 523 def set_auth(domain, user, passwd) uri = urify(domain) @www_auth.set_auth(uri, user, passwd) reset_all end |
#set_basic_auth(domain, user, passwd) ⇒ Object
Deprecated. Use set_auth instead.
530 531 532 533 534 |
# File 'lib/httpclient.rb', line 530 def set_basic_auth(domain, user, passwd) uri = urify(domain) @www_auth.basic_auth.set(uri, user, passwd) reset_all end |
#set_cookie_store(filename) ⇒ Object
Sets the filename where non-volatile Cookies be saved by calling save_cookie_store. This method tries to load and managing Cookies from the specified file.
Calling this method resets all existing sessions.
551 552 553 554 555 |
# File 'lib/httpclient.rb', line 551 def (filename) @cookie_manager. = filename @cookie_manager. if filename reset_all end |
#set_proxy_auth(user, passwd) ⇒ Object
Sets credential for Proxy authentication.
- user
-
username String.
- passwd
-
password String.
Calling this method resets all existing sessions.
541 542 543 544 |
# File 'lib/httpclient.rb', line 541 def set_proxy_auth(user, passwd) @proxy_auth.set_auth(user, passwd) reset_all end |
#strict_redirect_uri_callback(uri, res) ⇒ Object
A method for redirect uri callback. How to use:
clnt.redirect_uri_callback = clnt.method(:strict_redirect_uri_callback)
This callback does not allow relative redirect such as
Location: ../foo/
in HTTP header. (raises BadResponseError instead)
651 652 653 654 655 656 657 658 659 660 661 |
# File 'lib/httpclient.rb', line 651 def strict_redirect_uri_callback(uri, res) newuri = urify(res.header['location'][0]) if https?(uri) && !https?(newuri) raise BadResponseError.new("redirecting to non-https resource") end if !http?(newuri) && !https?(newuri) raise BadResponseError.new("unexpected location: #{newuri}", res) end puts "redirect to: #{newuri}" if $DEBUG newuri end |
#trace(uri, *args, &block) ⇒ Object
Sends TRACE request to the specified URL. See request for arguments.
732 733 734 |
# File 'lib/httpclient.rb', line 732 def trace(uri, *args, &block) request('TRACE', uri, argument_to_hash(args, :query, :header), &block) end |
#trace_async(uri, *args) ⇒ Object
Sends TRACE request in async style. See request_async for arguments. It immediately returns a HTTPClient::Connection instance as a result.
875 876 877 878 |
# File 'lib/httpclient.rb', line 875 def trace_async(uri, *args) query, body, header = keyword_argument(args, :query, :body, :header) request_async(:trace, uri, query, body, header || {}) end |