make a http request with a custom body as form url encoded in ruby

To make an HTTP request with a custom body as form URL encoded, you can use the Net::HTTP library in Ruby. The following code snippet demonstrates how to make such a request:

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

# Prepare the URI and form data
uri = URI.parse('https://example.com/api')
form_data = URI.encode_www_form({ 'name' => 'John Doe', 'email' => 'john@example.com' })

# Create a new HTTP POST request
request = Net::HTTP::Post.new(uri.request_uri)
request.body = form_data
request.content_type = 'application/x-www-form-urlencoded'

# Send the request and get the response
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
  http.request(request)
end

# Print the response body
puts response.body
567 chars
20 lines

In this example, the URI class is used to parse the request URL, and the URI.encode_www_form method is used to encode the form data as a URL-encoded string. The Net::HTTP::Post class is used to create a new HTTP POST request, and the request.body property is set to the encoded form data. Lastly, the request.content_type property is set to application/x-www-form-urlencoded to indicate that the request body is in URL-encoded format.

The Net::HTTP.start method is used to send the request and get the response, and the response.body property is used to print the response body to the console.

gistlibby LogSnag