Skip to content

Instantly share code, notes, and snippets.

@dineshsprabu
Last active December 2, 2016 13:51
Show Gist options
  • Save dineshsprabu/35bb1a8b3ee3acd471b1dca3366f3ad7 to your computer and use it in GitHub Desktop.
Save dineshsprabu/35bb1a8b3ee3acd471b1dca3366f3ad7 to your computer and use it in GitHub Desktop.
[RUBY] Fire and Forget HTTP Request with Net::HTTP
require 'net/https'
require 'json'
class Net::HTTPGenericRequest
#overriding request execution on Net::HTTP
def exec(sock, ver, path)
custom_request_method sock, ver, path, @body
end
private
#method to write request header and body on the socket and close.
def custom_request_method(sock, ver, path, body)
self.content_length = body.bytesize
delete 'Transfer-Encoding'
supply_default_content_type
write_header sock, ver, path
sock.write body
sock.close
end
end
end_url = URI.parse "https://httpbin.org/post"
payload = {id: 1}
http = Net::HTTP.new(end_url.host, end_url.port)
# http.use_ssl = true #uncomment to enable ssl.
request = Net::HTTP::Post.new(end_url.request_uri) #making a POST req for this example.
request['Content-Type'] = 'application/json'
request.body = payload.to_json
begin
http.request(request)
rescue IOError
p "Socket closed after firing request."
rescue Exception => e
p "Error on HTTP request - #{e.message}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment