检查https状态代码ruby

时间:2012-10-02 06:41:04

标签: ruby-on-rails ruby https

有没有办法在ruby中检查HTTPS状态代码?我知道有很多方法可以使用require 'net/http'在HTTP中执行此操作,但我正在寻找HTTPS。也许我需要使用不同的库?

4 个答案:

答案 0 :(得分:13)

您可以在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"

参考文献:

答案 1 :(得分:8)

您可以使用Net :: HTTP(S)周围的任何包装器来获得更容易的行为。 我在这里使用法拉第(https://github.com/lostisland/faraday),但HTTParty具有几乎相同的功能(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

(作为奖励,您可以选择解析响应,提高状态异常,记录请求....

 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")

答案 2 :(得分:5)

require 'uri'  
require 'net/http'  

res = Net::HTTP.get_response(URI('http://www.example.com/index.html'))  
puts res.code # -> '200'

答案 3 :(得分:1)

更具可读性的方式:

Start-Process -WindowStyle Hidden code .