November 17, 2016
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.
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
##
## ...
##
uri = URI('http://webservice.com/index.html?query=teststring')
res = Net::HTTP.get(uri)
put res.body if res.is_a?(Net::HTTPSuccess)
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)
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)
# 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?