Ruby:将curl命令转换为Ruby net/http请求

Ruby: convert curl command into Ruby net/http request

我想将此命令行 curl 命令转换为 Ruby net/http 请求:

curl -u user:pword --insecure -XGET "https://192.168.10.10:3000/_search/template?pretty=true" -H 'Content-Type:application/json' -d'{"id":"search_template_services", "params":{"environment":"prod","start_time":"2019-01-01T00:00:00.000Z","end_time":"2020-01-01T00:00:00.000Z","cantons":["AG"],"service":"WMS","request":"getmap"}}'

我的尝试:

endpoint = 'https://192.168.10.10:3000/_search/template/?pretty=true&id=search_template_services&environment=prod&start_time=2019-01-01T00:00:00.000Z&end_time=2020-01-01T00:00:00.000Z&cantons=AG&service=WMS&request=getmap'

puts "url: #{endpoint}"
uri = URI(endpoint)

Net::HTTP.start(uri.host, uri.port,
                use_ssl: uri.scheme == 'https',
                verify_mode: OpenSSL::SSL::VERIFY_NONE) do |http|
  request = Net::HTTP::Get.new uri.request_uri
  request.basic_auth('user', 'pword')
  @response = http.request request
end

data = JSON.parse(@response)

但我收到错误消息:

/usr/lib/ruby/2.4.0/json/common.rb:156:in `initialize': no implicit conversion of Net::HTTPBadRequest into String (TypeError)

显然 URL 不正确。如果我使用 curl 它会起作用。

如何修复 net/http 请求?

这是一个将许多(不是全部)curl 命令转换为 Ruby:

的网站

http://jhawthorn.github.io/curl-to-ruby

我运行你的curl命令通过这个。生成的 Ruby 代码似乎 运行,但由于它联系了私人服务器,我无法对其进行全面测试。这是代码:

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

uri = URI.parse("https://192.168.10.10:3000/_search/template?pretty=true")
request = Net::HTTP::Get.new(uri)
request.basic_auth("user", "pword")
request.content_type = "application/json"
request.body = JSON.dump({
  "id" => "search_template_services",
  "params" => {
    "environment" => "prod",
    "start_time" => "2019-01-01T00:00:00.000Z",
    "end_time" => "2020-01-01T00:00:00.000Z",
    "cantons" => [
      "AG"
    ],
    "service" => "WMS",
    "request" => "getmap"
  }
})

req_options = {
  use_ssl: uri.scheme == "https",
  verify_mode: OpenSSL::SSL::VERIFY_NONE,
}

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

# response.code
# response.body