make a http post request in ruby

Here is an example of how to make a HTTP POST request in Ruby using the Net::HTTP library:

main.rb
require 'net/http'

url = URI("https://www.example.com/api/resource")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true # Enable SSL/TLS

request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request.body = "{ \"key\": \"value\" }"

response = http.request(request)

puts response.code
puts response.body
343 chars
16 lines

In this example, we create a Net::HTTP::Post object and set the appropriate request headers and body. Then we create a Net::HTTP object, specify the target URL and send the request using http.request(request). Finally, we output the response code and body to the console.

related categories

gistlibby LogSnag