Recaptcha using Ruby without other requirements

This post is a collection of code snippets about how to make HTTP requests and parse the response. Also as example I included how to verify a Recaptcha field using the API from Google.

If you don't care about the theory or doing it yourself, just use this simple gem I made to re-use all of this.

Table of Contents


Google's ReCaptcha:

The example is pretty straight forward

require 'net/http'
require 'json'

##
## ...
##

uri = URI.parse('https://www.google.com/recaptcha/api/siteverify')

RECAPTCHA_API_SECRET = "" # From the Google Devlopers Console
REMOTE_USER_IP = ""       # User IP Address, in Sinatra is: request.ip
RECAPTCHA_RESPONSE = ""   # Request field, in Sinatra is: params["g-recaptcha-response"]

params = {
  'secret'    => RECAPTCHA_API_SECRET,
  'remoteip'  => REMOTE_USER_IP,
  'response'  => RECAPTCHA_RESPONSE
}

res = Net::HTTP.post_form(uri, params)

json_res = JSON.parse res.body if res.is_a?(Net::HTTPSuccess)

if json_res and json_res['success'] != true
  puts "Recaptcha solved!"
else
  puts "Wrong Captcha"
end

##
## ...
##

Simplest GET request

uri = URI('http://webservice.com/index.html?query=teststring')
res = Net::HTTP.get(uri)

put res.body if res.is_a?(Net::HTTPSuccess)

GET Request w/ dynamic parameters

uri = URI('http://webservice.com/index.html')
params = { :query => 'texttext', :page => 69 }
uri.query = URI.encode_www_form(params)

res = Net::HTTP.get_response(uri)
puts res.body if res.is_a?(Net::HTTPSuccess)

POST Request

This one is the one used in the ReCaptcha snippet.

uri = URI('http://webservice.com/search.php')
res = Net::HTTP.post_form(uri, 'query' => 'help me jesus', 'page' => 1)

puts res.body if res.is_a?(Net::HTTPSuccess)

Handling the Response

# Test Request
uri = URI('http://webservice.com/index.html')
res = Net::HTTP.get_response(uri)

# HTTP Status
puts res.code       # => '200'
puts res.message    # => 'OK'
puts res.class.name # => 'HTTPOK'

# Response Headers
puts res['Set-Cookie']   # => String
puts "Headers: #{res.to_hash.inspect}"

# Response Content
puts res.body if res.response_body_permitted?
About
Related Posts
Comments
The comments are closed on this section.
Hire me!

I'm currently open for new projects or join pretty much any project i may fit in, let me know!

Read about what I do, or contact me for details.