Class ThinHTTP
In: lib/thin_http.rb
Parent: Object

Synopsis

ThinHTTP is a light-weight and user friendly HTTP library. This class is useful for sending simple GET requests or uploading files via POST.

By default, it sends URL encoded data (application/x-www-form-urlencoded). MIME multipart encoded data (multipart/form-data) can be sent by utilizing the MIME library or the MultipartFormData class.

Features

  • Implements GET and POST requests.
  • Follows redirects using GET requests and set instance‘s host, port, and path attributes using the final destination URI.
  • Accepts either a params hash or an encoded string for POST and GET requests.
  • User-defined headers are sent with each request.
  • Sends and receives cookies automatically.
  • HTTP support only (HTTPS will be implemented when needed).

Design Goals

  • Extremely simple implementation and easy to use interface.
  • Only implement what is absolutely necessary.
  • Adhere to the RFCs.
  • Utilize third party libraries for added functionality when appropriate (i.e. MIME library for constructing multipart/form-data POSTs).
  • Build lightly on top of the standard Net::HTTP library.
  • Useful as a test tool in unit and integration testing (original design goal).

Examples

GET Request

  th = ThinHTTP.new('rubyforge.org', 80)
  th.set_header('User-Agent', th.class.to_s)
  response = th.get('/')

POST Request (URL encoding)

  th = ThinHTTP.new('example.com')
  response = th.post('/submit_form', :param1 => 'val1', :param2 => 'val2')

POST Request (multipart/form-data encoding using MIME library)

  fd = MIME::MultipartMedia::FormData.new
  fd.add_entity(MIME::TextMedia.new('Clint'), 'first_name')
  fd.add_entity(MIME::DiscreteMediaFactory.create('/tmp/pic.jpg'), 'portrait')

  th = ThinHTTP.new('example.com')
  response = th.post('/upload_file', fd.body, fd.content_type)

More Examples

  • Check the MultipartFormData class examples
  • Check the ThinHTTPTest class source code

Methods

get   host=   new   port=   post   set_header   unset_header  

Attributes

cookies  [RW] 
host  [R] 
path  [RW] 
port  [R] 
request_headers  [RW] 
response_headers  [RW] 

Public Class methods

Assign initial connection params for host, port, and http_headers. No connection is established until an HTTP method is invoked.

Public Instance methods

Send params to path as a GET request and return the response body.

params may be a URL encoded String or a Hash.

Change the remote connection host.

Change the remote connection port.

Send params to path as a POST request and return the response body.

params may be a String or a Hash. If params is a String, it is considered encoded data and content_type must be set accordingly. Otherwise, the params Hash is URL encoded.

Set the name header and its value in each request.

Delete the name header, thus not setting name in subsequent requests.

[Validate]