3

I'd like to convert this command line curl command into a Ruby net/http request:

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"}}'

my attempt:

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)

But I'm getting the error:

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

Apparently the URL isn't correct. If I use the curl it works.

How to fix the net/http request?

0

1 Answer 1

2

Here's a web site that converts many (not all) curl commands to Ruby:

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

I ran your curl command through this. The generated Ruby code appears to run, but since it contacts a private server I cannot fully test it. Here is the code:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.