在ruby中执行curl命令

时间:2015-10-20 08:49:48

标签: ruby-on-rails ruby

任何人都可以告诉我如何在ruby中编写这个命令

curl -i -u USERNAME https://api.github.com/repos/USERNAME/REPOSITORY/forks

3 个答案:

答案 0 :(得分:0)

您可以使用Hurley执行此操作。

首先安装gem:

$ gem install hurley

然后运行这个:

require "hurley"
require "json"

client = Hurley::Client.new "https://api.github.com"

repository = {
  username: "repo_username",
  name: "repo_name",
}

authentication = {
  username: "XXX",
  password: "YYY",
}

response = client.get("/repos/#{repository[:username]}/#{repository[:name]}/forks") do |req|
  req.header[:accept] = "application/vnd.github.preview+json"
  req.url.user = authentication[:username]
  req.url.password = authentication[:password]
end

puts JSON.parse(response.body)

答案 1 :(得分:0)

请查看HttpParty此帮助您发送GETPOSTPUTDELETE请求远程服务器,您可以发送{{1}并发送AuthenticationURL Data

对于您的情况,将Gem添加到您的宝石文件后

Post data

如果您希望在您的案例中发送任何数据,而不是要发送的数据,则正文为哈希值; response = HTTParty.get("https://api.github.com/repos/USERNAME/REPOSITORY/forks", body:{}, basic_auth: {username: 'USERNAME', password: 'PASSWORD'} ) if response && response.body # parse to json if you know that the responce is json otherwise work with the response whatever you want to do. json=JSON.parse(response.body) end 要发送Basic Auth您应该替换username and passwordUSERNAME用你的用户名和密码。

答案 2 :(得分:0)

通过避免外部依赖性,您还可以使用普通的Net::HTTP

require "net/http"

username = "USERNAME"
password = "PASSWORD"
repository = "REPOSITORY"

url = "https://api.github.com/repos/#{username}/#{repository}/forks"
uri = URI.parse(url)
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http|
  request = Net::HTTP::Head.new(uri)
  request.basic_auth(username, password)
  response = http.request(request)
  puts response.to_hash.inspect
end

如果您已启用TFA(双因素身份验证),则可以按照here所述创建访问令牌并使用它代替密码。