Ruby Tricks 2 - Net::HTTP and HTTPS/ SSL

I have been using RSpec to test an API and calling web services is a natural part of the work – so, I find myself going back to the Net::HTTP documentation from time to time. Most of the items are quite standard and the very well-written page (almost a cheatsheet) is at: https://docs.ruby-lang.org/en/2.7.0/Net/HTTP.html

This page is created basically on the back of the documentation page just to remind me how to do this. If it helps someone else, that’s a bonus!

There was one piece of code that I found very interesting and I wanted to bookmark it for later use – so, I’m adding it to this Notepad for memory. The code centres around using HTTPS/SSL. During development, especially locally, it’s common to not have HTTPS/SSL set up while the staging and production environments have SSL enabled and HTTPS URLs.

Making calls to HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl= and commonly, the code looks like:

1
2
3
4
5
6
7
8
9
require 'net/http'
require 'open-uri'

uri = URI('https://secure.example.com/some_path?query=string')

Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
  request = Net::HTTP::Get.new uri
  response = http.request request # Net::HTTPResponse object
end

The sample is directly from the Ruby 2.7.0 Net::HTTP documentation but I also found another example from the Ruby 2.0.0 Net::HTTP documentation which looks like the simplest and most elegant code to set use_ssl by inspecting the uri.scheme – it does this by doing :use_ssl => uri.scheme == 'https' as shown in the sample below.

1
2
3
4
5
6
7
8
9
10
11
require 'net/http'
require 'open-uri'

uri = URI('https://secure.example.com/some_path?query=string')

Net::HTTP.start(uri.host, uri.port,
  :use_ssl => uri.scheme == 'https') do |http|
  request = Net::HTTP::Get.new uri

  response = http.request request # Net::HTTPResponse object
end

For completeness, it should be noted that doing Net::HTTP.get(uri) will automatically turn on TLS verification if the URI object has a ‘https’ URI scheme, and that in newer versions of Ruby, you do not need to require ‘net/https’ to use HTTPS.

comments powered by Disqus