Class: HTTPClient

Inherits:
Object
  • Object
show all
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

OAuthClient

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.4'
@@dns_cache =
HTTPClient::LRUCache.new(ttl: 600, soft_ttl: 300, retry_delay: 60)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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')


390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/httpclient.rb', line 390

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

WebAgent::CookieManager

Cookies configurator.



323
324
325
# File 'lib/httpclient.rb', line 323

def cookie_manager
  @cookie_manager
end

#follow_redirect_countObject

How many times get_content and post_content follows HTTP redirect. 10 by default.



337
338
339
# File 'lib/httpclient.rb', line 337

def follow_redirect_count
  @follow_redirect_count
end

#proxy_authObject (readonly)

HTTPClient::ProxyAuth

Proxy authentication handler.



332
333
334
# File 'lib/httpclient.rb', line 332

def proxy_auth
  @proxy_auth
end

#request_filterObject (readonly)

An array of request filter which can trap HTTP request/response. See HTTPClient::WWWAuth to see how to use it.



330
331
332
# File 'lib/httpclient.rb', line 330

def request_filter
  @request_filter
end

#ssl_configObject (readonly)

HTTPClient::SSLConfig

SSL configurator.



321
322
323
# File 'lib/httpclient.rb', line 321

def ssl_config
  @ssl_config
end

#test_loopback_responseObject (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.



327
328
329
# File 'lib/httpclient.rb', line 327

def test_loopback_response
  @test_loopback_response
end

#www_authObject (readonly)

HTTPClient::WWWAuth

WWW authentication handler.



334
335
336
# File 'lib/httpclient.rb', line 334

def www_auth
  @www_auth
end

Class Method Details

.dns_cacheObject



235
236
237
# File 'lib/httpclient.rb', line 235

def self.dns_cache
  @@dns_cache
end

Instance Method Details

#cookiesObject

Returns stored cookies.



564
565
566
567
568
# File 'lib/httpclient.rb', line 564

def cookies
  if @cookie_manager
    @cookie_manager.cookies
  end
end

#debug_devObject

Returns debug device if exists. See debug_dev=.



428
429
430
# File 'lib/httpclient.rb', line 428

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.



436
437
438
439
440
# File 'lib/httpclient.rb', line 436

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.



667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/httpclient.rb', line 667

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.



711
712
713
# File 'lib/httpclient.rb', line 711

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.



846
847
848
849
# File 'lib/httpclient.rb', line 846

def delete_async(uri, *args)
  header = keyword_argument(args, :header)
  request_async(:delete, uri, nil, nil, header || {})
end

#download_file(uri, file, *args) ⇒ Object



735
736
737
738
739
740
741
742
# File 'lib/httpclient.rb', line 735

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.



689
690
691
# File 'lib/httpclient.rb', line 689

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.



818
819
820
821
# File 'lib/httpclient.rb', line 818

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.



603
604
605
606
# File 'lib/httpclient.rb', line 603

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.



684
685
686
# File 'lib/httpclient.rb', line 684

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.



811
812
813
814
# File 'lib/httpclient.rb', line 811

def head_async(uri, *args)
  query, header = keyword_argument(args, :query, :header)
  request_async(:head, uri, query, nil, header || {})
end

#keep_webmock_compatObject

webmock 1.6.2 depends on HTTP::Message#body.content to work. let’s keep it work iif webmock is loaded for a while.



414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/httpclient.rb', line 414

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_proxyObject

Returns NO_PROXY setting String if given.



478
479
480
# File 'lib/httpclient.rb', line 478

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.



493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/httpclient.rb', line 493

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.



716
717
718
# File 'lib/httpclient.rb', line 716

def options(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.



853
854
855
856
# File 'lib/httpclient.rb', line 853

def options_async(uri, *args)
  header = keyword_argument(args, :header)
  request_async(:options, uri, nil, nil, header || {})
end

#own_methodsObject



239
240
241
# File 'lib/httpclient.rb', line 239

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.



706
707
708
# File 'lib/httpclient.rb', line 706

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.



839
840
841
842
# File 'lib/httpclient.rb', line 839

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.



696
697
698
# File 'lib/httpclient.rb', line 696

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.



825
826
827
828
# File 'lib/httpclient.rb', line 825

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.



640
641
642
643
# File 'lib/httpclient.rb', line 640

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.



721
722
723
# File 'lib/httpclient.rb', line 721

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.



860
861
862
863
# File 'lib/httpclient.rb', line 860

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.



726
727
728
# File 'lib/httpclient.rb', line 726

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.



867
868
869
870
# File 'lib/httpclient.rb', line 867

def proppatch_async(uri, *args)
  body, header = keyword_argument(args, :body, :header)
  request_async(:proppatch, uri, nil, body, header || {})
end

#proxyObject

Returns URI object of HTTP proxy if exists.



443
444
445
# File 'lib/httpclient.rb', line 443

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.



457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/httpclient.rb', line 457

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.



701
702
703
# File 'lib/httpclient.rb', line 701

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.



832
833
834
835
# File 'lib/httpclient.rb', line 832

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)


578
579
580
# File 'lib/httpclient.rb', line 578

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.



782
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
# File 'lib/httpclient.rb', line 782

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.



883
884
885
886
# File 'lib/httpclient.rb', line 883

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.



890
891
892
893
# File 'lib/httpclient.rb', line 890

def reset(uri)
  uri = urify(uri)
  @session_manager.reset(uri)
end

#reset_allObject

Resets all of internal sessions. Keep-alive connections are disconnected.



896
897
898
# File 'lib/httpclient.rb', line 896

def reset_all
  @session_manager.reset_all
end

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)



559
560
561
# File 'lib/httpclient.rb', line 559

def save_cookie_store
  @cookie_manager.save_cookies
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.



522
523
524
525
526
# File 'lib/httpclient.rb', line 522

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.



529
530
531
532
533
# File 'lib/httpclient.rb', line 529

def set_basic_auth(domain, user, passwd)
  uri = urify(domain)
  @www_auth.basic_auth.set(uri, user, passwd)
  reset_all
end

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.



550
551
552
553
554
# File 'lib/httpclient.rb', line 550

def set_cookie_store(filename)
  @cookie_manager.cookies_file = filename
  @cookie_manager.load_cookies 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.



540
541
542
543
# File 'lib/httpclient.rb', line 540

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)



650
651
652
653
654
655
656
657
658
659
660
# File 'lib/httpclient.rb', line 650

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.



731
732
733
# File 'lib/httpclient.rb', line 731

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.



874
875
876
877
# File 'lib/httpclient.rb', line 874

def trace_async(uri, *args)
  query, body, header = keyword_argument(args, :query, :body, :header)
  request_async(:trace, uri, query, body, header || {})
end