basic_auth
是一個Net::HTTP
對象的實例方法。爲了方便起見,您可以定義一個具有期望的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')