Skip to content

Instantly share code, notes, and snippets.

@jdfight
Created August 31, 2016 22:48
Show Gist options
  • Save jdfight/289de7c0104c39826b92994642c7b569 to your computer and use it in GitHub Desktop.
Save jdfight/289de7c0104c39826b92994642c7b569 to your computer and use it in GitHub Desktop.
Ruby shell script to test get/post form data to web apis
#!/usr/bin/env ruby
require "uri"
require "net/http"
require "optparse"
options = {}
optparse = OptionParser.new do|opts|
# Set a banner, displayed at the top
# of the help screen.
opts.banner = "Usage: posttool -m GET/POST -u URL -q KEY,VAL..."
# Define the options, and what they do
options[:url] = ""
options[:query] = []
opts.on( '-u', '--url url', 'URL' ) do |url|
options[:url] = url
end
opts.on( '-q', '--query field,val..', Array, 'Form fields and values: fieldname, value... Ex: id,1,name,John Doe,Age,25, etc...' ) do |query|
options[:query] = query
end
opts.on('-m', '--mode get/post', 'GET/POST') do |mode|
options[:mode] = mode
end
# This displays the help screen, all programs are
# assumed to have this option.
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
optparse.parse!
# Convert the query list into hash values
hashquery = {}
options[:query].each.with_index do |k, v|
hashquery[k] = options[:query][v + 1] if v % 2 == 0
end
# post form data if mode is POST - otherwise, just use GET
if options[:mode].upcase == "POST"
uri = URI(options[:url])
res = Net::HTTP.post_form(uri, hashquery)
puts res.body
else
puts "get request"
uri = URI(options[:url])
uri.query = URI.encode_www_form(hashquery)
puts Net::HTTP.get(uri)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment