如何将用户和密码的curl请求转换为rubys NET :: HTTP for https site?

时间:2016-12-16 00:56:35

标签: ruby rest curl confluence confluence-rest-api

我有一个ruby脚本,我用来从网页获取信息并更新页面。我从网页上获得了一些json信息:

`curl -s -u #{username}:#{password} -X PUT -H 'Content-Type: application/json' -d'#{new_page_json_info}' #{HTTPS_PAGE_URL}`

然后我用以下内容更新页面:

Net::HTTP

我想用{{1}}来代替。我怎么能这样做?

这里参考的是我用来创建curl命令的confluence文档:https://developer.atlassian.com/confdev/confluence-server-rest-api/confluence-rest-api-examples

2 个答案:

答案 0 :(得分:0)

可以尝试做类似的事情:

uri = URI.parse("http://google.com/")

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth("username", "password")

答案 1 :(得分:0)

谢谢http://jhawthorn.github.io/curl-to-ruby 这解决了它。您所要做的就是为该网站提供curl命令,并将其转换为ruby脚本。

对于第一个curl(这从页面获取json信息并将其发送到stdout):

#!/usr/bin/env ruby

require 'net/http'
require 'uri'

uri = URI.parse("https://my.page.io/rest/api/content/")
request = Net::HTTP::Get.new(uri)
request.basic_auth("username", "password")

req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

# response.code
puts JSON.parse(response.body).to_hash 

对于第二个(这会更新页面上的json信息):

#!/usr/bin/env ruby

require 'net/http'
require 'uri'
require 'json'

uri = URI.parse("https://my.page.io/rest/api/content/")
request = Net::HTTP::Put.new(uri)
request.basic_auth("username", "password")
request.content_type = "application/json"
request.body = "{Test:blah}"

req_options = {
  use_ssl: uri.scheme == "https",
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end