有人知道如何使用RestClient进行基本身份验证吗?
我需要通过GitHub的RESTful API创建一个私有仓库。
最简单的方法是在URL中嵌入细节:
RestClient.get "http://username:password@example.com"
这是一个可选的basicauth工作代码示例,但不要求用户和密码嵌入URL中:
def get_collection(path)
response = RestClient::Request.new(
:method => :get,
:url => "#{@my_url}/#{path}",
:user => @my_user,
:password => @my_pass,
:headers => { :accept => :json, :content_type => :json }
).execute
results = JSON.parse(response.to_str)
end
请注意,如果@my_user
和@mypass
没有被实例化,它可以在没有basicauth的情况下正常工作。
RestClient::Request
并添加更多上下文以使您提供的示例完全可用。 - Michael Wasser
RestClient::Request.execute(
method: :post,
url: "https://example.com",
headers: { "Authorization" => "Basic " + Base64::encode64(auth_details) },
payload: { "foo" => "bar"}
)
def auth_details
ENV.fetch("HTTP_AUTH_USERNAME") + ":" + ENV.fetch("HTTP_AUTH_PASSWORD")
end
RestClient.get("https://example.com",
{
Authorization: "Basic #{Base64::encode64('guest:guest')}"
}
)
RestClient.post("https://example.com",
{ }.to_json,
{
Authorization: "Basic #{Base64::encode64('guest:guest')}"
}
)