Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPS Requests in Ruby

Tags:

ruby

https

Is there a gem or library for HTTPS Requests in Ruby? What is it called and can you provide some example usage?

What I am trying to do is open a page, parse some text from it, and then output it.

like image 586
Soyak Avatar asked Oct 14 '12 15:10

Soyak


2 Answers

SSL Request with Ruby Standard Library

require 'net/http'
require 'uri'
Net::HTTP.get URI('https://encrypted.google.com')

Net::HTTP in Ruby (>= 2.0.0) performs SSL verification by default if you pass a URI object that has a "https" URL to it. See https://github.com/ruby/ruby/blob/778bbac8ac2ae50f0987c4888f7158296ee5bbdd/lib/net/http.rb#L481

You may verify this by performing a get request on a domain with an expired certificate.

uri = URI('https://expired.badssl.com/')
Net::HTTP.get(uri)
# OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: certificate verify failed

SSL Request with Ruby HTTP gems

If you wish to use an alternative, you may use the following gems that also performs SSL verification by default:

  1. Excon

Excon is a pure Ruby HTTP implementation.

require 'excon'
Excon.get 'https://encrypted.google.com'
  1. Curb

Curb is a HTTP client that uses libcurl under the hood.

require 'curl'
Curl.get 'https://encrypted.google.com'
  1. http.rb

HTTP or http.rb is a pure Ruby HTTP implementation but uses http_parser.rb to parse HTTP requests and responses. Since http_parser.rb uses native extensions, it claims to be one of the fastest HTTP client library. But as always, take benchmarks with a grain of salt.

require 'http'
HTTP.get 'https://encrypted.google.com'
  1. HTTPClient

HTTPClient is another pure Ruby implementation.

require 'httpclient'
HTTPClient.get 'https://encrypted.google.com'

What's listed here are HTTP libraries and not HTTP wrappers. Wrapper gems like HTTParty and Faraday either wrap around a particular HTTP implementation or use adapters to provide a unified HTTP interface. You may check out this Comparison matrix of Ruby HTTP client features. It compares the features of every single HTTP client library out there. But do note that the information isn't updated since 2012.

like image 135
8 revs, 2 users 66% Avatar answered Sep 27 '22 22:09

8 revs, 2 users 66%


There is an integrated library in the language called Net::HTTP

An example usage of it would be:

uri = URI('https://example.com/some_path?query=string')
response = Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri.request_uri
  http.request request # Net::HTTPResponse object
end
puts response.body

UPDATE: You need to include that library like this:

require 'net/https'
like image 27
Itay Grudev Avatar answered Sep 27 '22 20:09

Itay Grudev