class Patron::Session

This class represents multiple request/response transactions with an HTTP server. This is the primary API for Patron.

Attributes

auth_type[RW]

Set the authentication type for the request. @see Patron::Request#auth_type

base_url[RW]

Prepended to the URL in all requests.

buffer_size[RW]

Set the buffer size for this request. This option will only be set if #buffer_size is non-nil

cacert[RW]

What cacert file should this session use to verify SSL certificates?

connect_timeout[RW]

HTTP connection timeout in seconds. Defaults to 1 second.

default_response_charset[RW]

Default encoding of responses. Used if no charset is provided by the host.

force_ipv4[RW]

Force curl to use IPv4

headers[RW]

Standard set of headers that are used in all requests.

ignore_content_length[RW]

Does this session ignore Content-Size headers?

insecure[RW]

Does this session stricly verify SSL certificates?

max_redirects[RW]

Maximum number of times to follow redirects. Set to 0 to disable and -1 to follow all redirects. Defaults to 5.

password[RW]

Username and password for http authentication

proxy[RW]

Proxy URL in cURL format ('hostname:8080')

proxy_type[RW]

Proxy type (default is HTTP), see constants under ProxyType for supported types.

ssl_version[RW]

Specifies the ssl version

timeout[RW]

HTTP transaction timeout in seconds. Defaults to 5 seconds.

username[RW]

Username and password for http authentication

Public Class Methods

new(args = {}) { |self| ... } click to toggle source

Create a new Session object.

# File lib/patron/session.rb, line 93
def initialize(args = {}, &block)

  # Allows accessors to be set via constructor hash. Ex:  {:base_url => 'www.home.com'}
  args.each do |attribute, value|
    send("#{attribute}=", value)
  end

  # Allows accessors to be set via block.
  if block_given?
    yield self
  end

  @headers ||= {}
  @timeout ||= 5
  @connect_timeout ||= 1
  @max_redirects ||= 5
  @auth_type ||= :basic
  @force_ipv4 ||= false
end

Public Instance Methods

build_request(action, url, headers, options = {}) click to toggle source

Build a request object that can be used in handle_request

# File lib/patron/session.rb, line 220
def build_request(action, url, headers, options = {})
  # If the Expect header isn't set uploads are really slow
  headers['Expect'] ||= ''

  Request.new.tap do |req|
    req.action                 = action
    req.headers                = self.headers.merge headers
    req.timeout                = options.fetch :timeout,               self.timeout
    req.connect_timeout        = options.fetch :connect_timeout,       self.connect_timeout
    req.force_ipv4             = options.fetch :force_ipv4,            self.force_ipv4
    req.max_redirects          = options.fetch :max_redirects,         self.max_redirects
    req.username               = options.fetch :username,              self.username
    req.password               = options.fetch :password,              self.password
    req.proxy                  = options.fetch :proxy,                 self.proxy
    req.proxy_type             = options.fetch :proxy_type,            self.proxy_type
    req.auth_type              = options.fetch :auth_type,             self.auth_type
    req.insecure               = options.fetch :insecure,              self.insecure
    req.ssl_version            = options.fetch :ssl_version,           self.ssl_version
    req.cacert                 = options.fetch :cacert,                self.cacert
    req.ignore_content_length  = options.fetch :ignore_content_length, self.ignore_content_length
    req.buffer_size            = options.fetch :buffer_size,           self.buffer_size
    req.multipart              = options[:multipart]
    req.upload_data            = options[:data]
    req.file_name              = options[:file]

    base_url = self.base_url.to_s
    url = url.to_s
    raise ArgumentError, "Empty URL" if base_url.empty? && url.empty?
    uri = URI.parse(base_url.empty? ? url : File.join(base_url, url))
    query = uri.query.to_s.split('&')
    query += options[:query].is_a?(Hash) ? Util.build_query_pairs_from_hash(options[:query]) : options[:query].to_s.split('&')
    uri.query = query.join('&')
    uri.query = nil if uri.query.empty?
    url = uri.to_s
    req.url = url
  end
end
copy(url, dest, headers = {}) click to toggle source

Sends a WebDAV COPY request to the specified url.

# File lib/patron/session.rb, line 204
def copy(url, dest, headers = {})
  headers['Destination'] = dest
  request(:copy, url, headers)
end
delete(url, headers = {}) click to toggle source

As get but sends an HTTP DELETE request. Notice: this method doesn't accept any data argument: if you need to send data with a delete request, please, use the request method.

# File lib/patron/session.rb, line 164
def delete(url, headers = {})
  request(:delete, url, headers)
end
enable_debug(file = nil) click to toggle source

Enable debug output to stderr or to specified file.

# File lib/patron/session.rb, line 131
def enable_debug(file = nil)
  set_debug_file(file.to_s)
end
escape( string ) → escaped string click to toggle source

URL escapes the provided string.

static VALUE session_escape(VALUE self, VALUE value) {
  struct curl_state *state = get_curl_state(self);
  VALUE string = StringValue(value);
  char* escaped = NULL;
  VALUE retval = Qnil;

  escaped = curl_easy_escape(state->handle,
                             RSTRING_PTR(string),
                             (int) RSTRING_LEN(string));

  retval = rb_str_new2(escaped);
  curl_free(escaped);

  return retval;
}
Also aliased as: urlencode
get(url, headers = {}) click to toggle source

Retrieve the contents of the specified url optionally sending the specified headers. If the base_url varaible is set then it is prepended to the url parameter. Any custom headers are merged with the contents of the headers instance variable. The results are returned in a Response object. Notice: this method doesn't accept any data argument: if you need to send data with a get request, please, use the request method.

# File lib/patron/session.rb, line 146
def get(url, headers = {})
  request(:get, url, headers)
end
get_file(url, filename, headers = {}) click to toggle source

Retrieve the contents of the specified url as with get, but the content at the URL is downloaded directly into the specified file.

# File lib/patron/session.rb, line 152
def get_file(url, filename, headers = {})
  request(:get, url, headers, :file => filename)
end
handle_cookies(file = nil) click to toggle source

Turn on cookie handling for this session, storing them in memory by default or in file if specified. The file must be readable and writable. Calling multiple times will add more files.

# File lib/patron/session.rb, line 116
def handle_cookies(file = nil)
  if file
    path = Pathname(file).expand_path
    unless File.exists?(file) and File.writable?(path.dirname)
      raise ArgumentError, "Can't create file #{path} (permission error)"
    end
    unless File.readable?(file) or File.writable?(path)
      raise ArgumentError, "Can't read or write file #{path} (permission error)"
    end
  end
  enable_cookie_session(path.to_s)
  self
end
head(url, headers = {}) click to toggle source

As get but sends an HTTP HEAD request.

# File lib/patron/session.rb, line 157
def head(url, headers = {})
  request(:head, url, headers)
end
interrupt → session click to toggle source

Interrupt any currently executing request. This will cause the current request to error and raise an exception.

static VALUE session_interrupt(VALUE self) {
  struct curl_state *state = get_curl_state(self);
  state->interrupt = 1;
  return self;
}
post(url, data, headers = {}) click to toggle source

Uploads the passed data to the specified url using HTTP POST. data can be a string or a hash.

# File lib/patron/session.rb, line 181
def post(url, data, headers = {})
  if data.is_a?(Hash)
    data = data.map {|k,v| urlencode(k.to_s) + '=' + urlencode(v.to_s) }.join('&')
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
  end
  request(:post, url, headers, :data => data)
end
post_file(url, filename, headers = {}) click to toggle source

Uploads the contents of a file to the specified url using HTTP POST.

# File lib/patron/session.rb, line 190
def post_file(url, filename, headers = {})
  request(:post, url, headers, :file => filename)
end
post_multipart(url, data, filename, headers = {}) click to toggle source

Uploads the contents of a file and data to the specified url using HTTP POST.

# File lib/patron/session.rb, line 195
def post_multipart(url, data, filename, headers = {})
  request(:post, url, headers, {:data => data, :file => filename, :multipart => true})
end
put(url, data, headers = {}) click to toggle source

Uploads the passed data to the specified url using HTTP PUT. data must be a string.

# File lib/patron/session.rb, line 170
def put(url, data, headers = {})
  request(:put, url, headers, :data => data)
end
put_file(url, filename, headers = {}) click to toggle source

Uploads the contents of a file to the specified url using HTTP PUT.

# File lib/patron/session.rb, line 175
def put_file(url, filename, headers = {})
  request(:put, url, headers, :file => filename)
end
request(action, url, headers, options = {}) click to toggle source

Send an HTTP request to the specified url.

# File lib/patron/session.rb, line 214
def request(action, url, headers, options = {})
  req = build_request(action, url, headers, options)
  handle_request(req)
end
reset → session click to toggle source

Reset the underlying cURL session. This effectively closes all open connections and disables debug output.

static VALUE session_reset(VALUE self) {
  struct curl_state *state;
  Data_Get_Struct(self, struct curl_state, state);

  if (NULL != state->handle) {
    cleanup(self);
    curl_easy_cleanup(state->handle);
    state->handle = NULL;
    session_close_debug_file(state);
  }

  return self;
}
unescape( string ) → unescaped string click to toggle source

Unescapes the provided string.

static VALUE session_unescape(VALUE self, VALUE value) {
  struct curl_state *state = get_curl_state(self);
  VALUE string = StringValue(value);
  char* unescaped = NULL;
  VALUE retval = Qnil;

  unescaped = curl_easy_unescape(state->handle,
                                 RSTRING_PTR(string),
                                 (int) RSTRING_LEN(string),
                                 NULL);

  retval = rb_str_new2(unescaped);
  curl_free(unescaped);

  return retval;
}
Also aliased as: urldecode
urldecode(p1)
Alias for: unescape
urlencode(p1)
Alias for: escape

Private Instance Methods

handle_request( request ) → response click to toggle source

Peform the actual HTTP request by calling libcurl. Each filed in the request object will be used to set the appropriate option on the libcurl library. After the request completes, a Response object will be created and returned.

In the event of an error in the libcurl library, a Ruby exception will be created and raised. The exception will return the libcurl error code and error message.

static VALUE session_handle_request(VALUE self, VALUE request) {
  set_options_from_request(self, request);
  return rb_ensure(&perform_request, self, &cleanup, self);
}
set_debug_file( file ) → session click to toggle source

Enable debug output to stderr or to specified file.

static VALUE set_debug_file(VALUE self, VALUE file) {
  struct curl_state *state = get_curl_state(self);
  char* file_path = RSTRING_PTR(file);

  session_close_debug_file(state);

  if(file_path != NULL && strlen(file_path) != 0) {
    state->debug_file = open_file(file, "wb");
  } else {
    state->debug_file = stderr;
  }

  return self;
}