Class: TwoCaptcha::HTTP
- Inherits:
-
Object
- Object
- TwoCaptcha::HTTP
- Defined in:
- lib/two_captcha/http.rb
Overview
TwoCaptcha::HTTP exposes common HTTP routines that can be used by the TwoCaptcha API client.
Class Method Summary collapse
-
.open_url(url) ⇒ String
Retrieve the contents of a captcha URL supporting HTTPS and redirects.
-
.prepare_multipart_data(payload) ⇒ String
Prepare the multipart data to be sent via a :multipart request.
-
.request(options = {}) ⇒ String
Perform an HTTP request with support to multipart requests.
Class Method Details
.open_url(url) ⇒ String
Retrieve the contents of a captcha URL supporting HTTPS and redirects.
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/two_captcha/http.rb', line 12 def self.open_url(url) uri = URI(url) http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end res = http.get(uri.request_uri) if (redirect = res.header['location']) open_url(redirect) else res.body end end |
.prepare_multipart_data(payload) ⇒ String
Prepare the multipart data to be sent via a :multipart request.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/two_captcha/http.rb', line 84 def self.prepare_multipart_data(payload) boundary = 'randomstr' + rand(1_000_000).to_s # a random unique string content = [] payload.each do |param, value| content << '--' + boundary content << "Content-Disposition: form-data; name=\"#{param}\"" content << '' content << value end content << '--' + boundary + '--' content << '' [boundary, content.join("\r\n")] end |
.request(options = {}) ⇒ String
Perform an HTTP request with support to multipart requests.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/two_captcha/http.rb', line 41 def self.request( = {}) uri = URI([:url]) method = [:method] || :get payload = [:payload] || {} timeout = [:timeout] || 60 headers = { 'User-Agent' => TwoCaptcha::USER_AGENT } case method when :get uri.query = URI.encode_www_form(payload) req = Net::HTTP::Get.new(uri.request_uri, headers) when :post req = Net::HTTP::Post.new(uri.request_uri, headers) req.set_form_data(payload) when :multipart req = Net::HTTP::Post.new(uri.request_uri, headers) boundary, body = prepare_multipart_data(payload) req.content_type = "multipart/form-data; boundary=#{boundary}" req.body = body else fail TwoCaptcha::ArgumentError, "Illegal HTTP method (#{method})" end http = Net::HTTP.new(uri.hostname, uri.port) http.use_ssl = true if (uri.scheme == 'https') http.open_timeout = timeout http.read_timeout = timeout res = http.request(req) res.body rescue Net::OpenTimeout, Net::ReadTimeout raise TwoCaptcha::Timeout end |