Ruby HTTP 中的默认 HTTP 基本身份验证

HTTP Basic Authentication as default in Ruby HTTP

使用Ruby 2.2.3 我正在寻找一种对每个请求都使用HTTP 基本身份验证的方法。我知道可以为每个请求定义 basic_auth

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth("username", "password")
response = http.request(request)

我如何"globally"使用basic_auth

basic_authNet::HTTP 对象的实例方法。为方便起见,您可以定义一个 class 并包含所需的 basic_auth 设置或作为参数给出。

简单示例:

require 'uri'
require 'net/http'

class SimpleHTTP

  def initialize uri, user = "default_user", pass = "default_pass"
    @uri = URI.parse(uri)
    @username = user
    @password = pass
  end

  def request path=nil
    @uri.path = path if path # use path if provided
    http = Net::HTTP.new(@uri.host, @uri.port)
    req = Net::HTTP::Get.new(@uri.request_uri)
    req.basic_auth(@username, @password)
    http.request(req)
  end


end

# Simple Example
http = SimpleHTTP.new('http://www.yoursite.com/defaultpath')
http.request

# Override default user/pass
http2 = SimpleHTTP.new('http://www.yoursite.com/defaultpath', "myusername", "mypass")
http2.request

# Provide path in request method
http = SimpleHTTP.new('http://www.yoursite.com/')
http.request('/some_path')