Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Net::HTTP.get for an https url

Tags:

ruby

I'm trying to use Net::HTTP.get() for an https URL:

@data = Net::HTTP.get(uri, Net::HTTP.https_default_port()) 

However, I get the following result when I try to print the results:

can't convert URI::HTTPS into String

What's the deal? I'm using Ruby 1.8.7 (OS X)

like image 481
Tony Stark Avatar asked Apr 26 '11 06:04

Tony Stark


People also ask

What is Net :: HTTP?

Net::HTTP provides a rich library which can be used to build HTTP user-agents. For more details about HTTP see [RFC2616](www.ietf.org/rfc/rfc2616.txt). Net::HTTP is designed to work closely with URI.


2 Answers

Original answer:

uri = URI.parse("https://example.com/some/path") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true @data = http.get(uri.request_uri) 

As pointed out in the comments, this is more elegant:

require "open-uri" @data = URI.parse("https://example.com/some/path").read 
like image 112
stef Avatar answered Oct 07 '22 01:10

stef


EDIT: My approach works, but @jason-yeo's approach is far easier.

It appears as of 2.1.2 the preferred a documented method is as follows (directly quoting the documentation):

HTTPS is enabled for an HTTP connection by #use_ssl=.

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  

In previous versions of Ruby you would need to require ‘net/https’ to use HTTPS. This is no longer true.

like image 42
eebbesen Avatar answered Oct 06 '22 23:10

eebbesen