Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check https status code ruby

Is there a way to check for an HTTPS status code in ruby? I know that there are ways to do this in HTTP using require 'net/http', but I'm looking for HTTPS. Maybe there is a different library that I need to use?

like image 982
locoboy Avatar asked Oct 02 '12 06:10

locoboy


3 Answers

You can do this in net/http:

require "net/https"
require "uri"

uri = URI.parse("https://www.secure.com/")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true

request = Net::HTTP::Get.new(uri.request_uri)
res = http.request(request)

res.code #=> "200"

Refs:

  • Net::HTTP cheat sheet
  • How to Cure Net::HTTP’s Risky Default HTTPS Behavior
like image 118
Chris Salzberg Avatar answered Nov 15 '22 04:11

Chris Salzberg


You can use any wrapper around Net::HTTP(S) to get much easier behavior. I use Faraday here ( https://github.com/lostisland/faraday ) but HTTParty has almost the same functionality ( https://github.com/jnunemaker/httparty )

 require 'faraday'

 res = Faraday.get("https://www.example.com/")
 res.status # => 200

 res = Faraday.get("http://www.example.com/")
 res.status # => 200

(as a bonus you get options for parsing responses, raising state exceptions, logging requests....

 connection = Faraday.new("https://www.example.com/") do |conn|
   # url-encode the body if given as a hash
   conn.request :url_encoded
   # add an authorization header
   conn.request :oauth2, 'TOKEN'
   # use JSON to convert the response into a hash
   conn.response :json, :content_type => /\bjson$/
   # ...
   conn.adapter Faraday.default_adapter
 end

 connection.get("/")

  # GET https://www.example.com/some/path?query=string
 connection.get("/some/path", :query => "string")

 # POST, PUT, DELETE, PATCH....
 connection.post("/some/other/path", :these => "fields", :will => "be converted to a request string in the body"}

 # add any number of headers. in this example "Accept-Language: en-US"
 connection.get("/some/path", nil, :accept_language => "en-US")
like image 31
rewritten Avatar answered Nov 15 '22 05:11

rewritten


require 'uri'  
require 'net/http'  

res = Net::HTTP.get_response(URI('http://www.example.com/index.html'))  
puts res.code # -> '200'
like image 5
mUser0 Avatar answered Nov 15 '22 06:11

mUser0