Ruby Net::HTTP cheat sheet

╰半夏微凉° 2022-05-14 01:15 231阅读 0赞

Update: It’s on GitHub now.


I always have to look up how to use Net::HTTP, and I never find what I’m looking for. Behold, a cheat sheet!

A basic request

  1. require "net/https"
  2. require "uri"
  3. uri = URI.parse("http://google.com")
  4. http = Net::HTTP.new(uri.host, uri.port)
  5. request = Net::HTTP::Get.new(uri.request_uri)
  6. request.initialize_http_header({"User-Agent" => "My Ruby Script"})
  7. response = http.request(request)
  8. puts response.code
  9. # => 301
  10. puts response["location"] # All headers are lowercase
  11. # => http://www.google.com/

URI

  1. uri = URI.parse("http://mysite.com/some_api")
  2. uri = URI.parse("https://mysite.com/thing?foo=bar")
  3. # URI will also guess the correct port
  4. URI.parse("http://foo.com").port # => 80
  5. URI.parse("https://foo.com/").port # => 443
  6. # Full reference
  7. uri = URI.parse("http://foo.com/this/is/everything?query=params")
  8. # p (uri.methods - Object.methods).sort
  9. p uri.scheme # => "http"
  10. p uri.host # => "foo.com"
  11. p uri.port # => 80
  12. p uri.request_uri # => "/this/is/everything?query=params"
  13. p uri.path # => "/this/is/everything"
  14. p uri.query # => "query=params"
  15. # There are setters as well
  16. uri.port = 8080
  17. uri.host = "google.com"
  18. uri.scheme = "ftp"
  19. p uri.to_s
  20. # => "ftp://google.com:8080/this/is/everything?query=param"

Everything else

  1. http = Net::HTTP.new(uri.host, uri.port)
  2. http.open_timeout = 3 # in seconds
  3. http.read_timeout = 3 # in seconds
  4. # The request.
  5. request = Net::HTTP::Get.new(uri.request_uri)
  6. # All the HTTP 1.1 methods are available.
  7. Net::HTTP::Get
  8. Net::HTTP::Post
  9. Net::HTTP::Put
  10. Net::HTTP::Delete
  11. Net::HTTP::Head
  12. Net::HTTP::Options
  13. request.body = "Request body here."
  14. request.initialize_http_header({"Accept" => "*/*"})
  15. request.basic_auth("username", "password")
  16. response = http.request(request)
  17. response.body
  18. response.status
  19. response["header-here"] # All headers are lowercase

SSL

  1. # Normal ssl
  2. http.use_ssl = true
  3. http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  4. # SSL .pem certs
  5. pem = File.read("/path/to/my.pem")
  6. http.use_ssl = true
  7. http.cert = OpenSSL::X509::Certificate.new(pem)
  8. http.key = OpenSSL::PKey::RSA.new(pem)
  9. http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  10. # Check for SSL dynamically. If your URI is https and you don't specify a
  11. # port, the port will be 443, which is the correct SSL port.
  12. http.use_ssl = (uri.port == 443)

发表评论

表情:
评论列表 (有 0 条评论,231人围观)

还没有评论,来说两句吧...

相关阅读