I'm trying to execute curl through Ruby script using two different methods and have some errors in both.
First method is using shell command
#!/usr/bin/ruby
`curl --cacert RepoCert --location --request POST 'https://test-service/rest/services/request/' --header 'Authorization: Basic amkkdksmmkk3XCf45DffSa23Ert' --header 'Content-Type: application/json' --data-binary "{ \"serviceID\": \"3\", \"TypeId\": \"52\", \"requestFieldValues\": { \"summary\": \"summary\", \"description\": \"something\", \"prority\": { \"id\": \"1\"}, \"customfield\": \"5\" }} "`
and I have an error
"Unexpected character (\u0027s\u0027 (code 115)): was expecting double-quote to start field name\n at [Source: com.itlab.jira.plugins.extender.helper.RequestWrapper$5db70c75; line:1, column:5]"
Also tried using Ruby Net::HTTP (code generated from https://jhawthorn.github.io/curl-to-ruby/)
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://test-service/rest/services/request/")
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Basic amkkdksmmkk3XCf45DffSa23Ert"
request.body = JSON.dump({
"serviceID" => "3",
"TypeId" => "52",
"requestFieldValues" => {
"summary" => "summary",
"description" => "something",
"prority" => {
"id" => "1"
},
"customfield" => "5"
}
})
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
and I get
/usr/share/ruby/net/http.rb:921:in `connect': SSL_connect returned=1 errno=0 state=error: certificate verify failed (OpenSSL::SSL::SSLError)
The problem is I have to use certificate authorization in this case so I can't ignore it.
Curl executed form command line is working fine. Any idea how to fix one of those methods (or both)?
Open3or the multi-argument form ofKernel#system. Those will bypass the shell and unwrap one layer of quoting/escaping. Then you can simple things likesystem('curl', '--cacert', 'RepoCert', ..., '--data-binary', ruby_hash.to_json)and stop worrying about who is interpreting which quotes and backslashes.system('curl', ...)is a really brutal way of doing this, you lose a lot of control. Using Net::HTTP is a step up, if a bit more tricky. I'd recommend Faraday which is both powerful and fairly easy to use.