Typhoeus : a gem for http requests in rails.

By | 2013 年 12 月 14 日

Typhoeus



Single request

request = Typhoeus::Request.new(
  "www.example.com",
  method: :post,
  body: "this is a request body",
  params: { field1: "a field" },
  headers: { Accept: "text/html" }
)

# handle the response as follows
request.on_complete do |response|
  if response.success?
    # hell yeah
  elsif response.timed_out?
    # aw hell no
    log("got a time out")
  elsif response.code == 0
    # Could not get an http response, something's wrong.
    log(response.return_message)
  else
    # Received a non-successful http response.
    log("HTTP request failed: " + response.code.to_s)
  end
end

# this will actually execute the request
request.run



Parallel requests
Typhoeus doing well in the parallel requests, just doing this:

hydra = Typhoeus::Hydra.hydra

first_request = Typhoeus::Request.new("www.example.com/posts/1.json")
first_request.on_complete do |response|
  third_request = Typhoeus::Request.new(www.example.com/posts/3.json)
  hydra.queue third_request
end
second_request = Typhoeus::Request.new("www.example.com/posts/2.json")

hydra.queue first_request
hydra.queue second_request
# this is a blocking call that returns once all requests are complete
hydra.run



Referrence
For more information, looking:
Typhoeus on Github

发表评论

电子邮件地址不会被公开。 必填项已用*标注