make a http request with a custom body as form data in ruby

To make an HTTP request with a custom body as form data in Ruby, you can use the Net::HTTP library. Here's an example code snippet:

main.rb
require 'net/http'
require 'uri'

# Set up the HTTP request
url = URI("http://example.com/api/endpoint")
req = Net::HTTP::Post.new(url)
req.set_form_data({ 'foo' => 'bar', 'baz' => 'qux' })

# Send the request and get the response
res = Net::HTTP.start(url.hostname, url.port) do |http|
  http.request(req)
end

puts res.body # prints the response body
353 chars
15 lines

In this example, we create a Net::HTTP::Post request with a URL and form data in the request body. We then send the request using Net::HTTP.start, which returns a Net::HTTPResponse. We can access the response body using res.body.

Note that if you need to specify custom headers, you can do so with req['Header-Name'] = 'Header Value' before sending the request.

gistlibby LogSnag