7

RubyでHTTPSステータスコードを確認する方法はありますか? を使用して HTTP でこれを行う方法があることは知っていますがrequire 'net/http'、HTTPS を探しています。多分私が使用する必要がある別のライブラリがありますか?

4

4 に答える 4

18

これは 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"

参照:

于 2012-10-02T07:03:32.370 に答える
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")
于 2012-10-02T08:24:30.150 に答える
5
require 'uri'  
require 'net/http'  

res = Net::HTTP.get_response(URI('http://www.example.com/index.html'))  
puts res.code # -> '200'
于 2014-02-25T11:29:42.300 に答える