簡體   English   中英

在Ruby中執行curl命令

[英]Executing curl command in ruby

誰能告訴我如何用ruby編寫此命令

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

您可以使用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)

看看HttpParty,它可以幫助您將GETPOSTPUTDELETE請求發送到遠程服務器,您可以發送Authentication並發送URL DataPost data

對於您的情況,是在將Gem添加到Gem文件之后:

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

如果您要發送任何數據,則正文是一個哈希,如果要發送任何數據,則為空,不發送任何數據,而要發送username and password Basic Auth身份Basic Auth ,則應使用username and password替換USERNAMEPASSWORD

通過避免外部依賴性,您還可以堅持使用簡單的舊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(雙重身份驗證)功能,則可以按此處所述創建訪問令牌並使用它代替密碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM