How do I do basic authentication with RestClient?

淺唱寂寞╮ 提交于 2019-11-28 17:50:41
Mike Buckbee

From the source it looks like you can just specify user and password as part of your request object.

Have you tried something like:

r = Request.new({:user => "username", :password => "password"})

Also if you look down in the Shell section of the ReadMe it has an example of specifying it as part of restshell.

$ restclient https://example.com user pass
>> delete '/private/resource'
opsb

The easiest way is to embed the details in the URL:

RestClient.get "http://username:password@example.com"
bgupta

Here is an example of working code where I support optional basicauth but don't require the user and password be embedded in the 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

Do note if @my_user and @mypass are not instantiated, it works fine without basicauth.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!