Net::HTTP Raw Post Ruby Code

Net::HTTP is still a popular option though it doesn’t have the easiest API to remember. In order to Post & Access posted request object from the ruby script example is shown below:

require “cgi”
require “uri”
require “net/http”

#To Post data without form using RESTful Method

url = URI.parse(“http://api.domain.com”)
begin
requestXml = “Johnjohn1234
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url.path)
request.body = requestXml
request[“Content-Type”] = “application/xml”
response = http.request(request)
response.code # => 200 Ok
response.body # => The body (HTML, XML, blob, whatever)
rescue
logger.debug “Error #{$!}”
end

#To Receive Posted raw data from RESTful Method
if request.post?
response = CGI::unescape(request.raw_post)
end

Permanent link to this article: https://blog.openshell.in/2011/03/nethttp-raw-post-ruby-code/

Leave a Reply

Your email address will not be published.