gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:45:53 25 4
gpt4 key购买 nike

我想将此命令行 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)



显然网址不正确。如果我使用 curl 它可以工作。

如何修复 net/http 请求?

最佳答案

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

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

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

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

关于Ruby:将 curl 命令转换为 Ruby net/http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59709491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com