A simple example of sending HTTP-based requests in Ruby programs.
1. Establish an HTTP connection (Send request parameters through GET)
Require "open-uri" # Write the GET Request Parameters in the uri url uri = 'HTTP: // uri 'html_response = nil open (uri) do | http | html_response = http. read end puts html_response require "open-uri" # Write the GET Request Parameters in the uri url uri = 'HTTP: // uri 'html_response = nil open (uri) do | http | html_response = http. read end puts html_response
2. Send request parameters through POST
Params = {} params ["name"] = 'Tom 'uri = URI. parse ("http: // uri") res = Net: HTTP. post_form (uri, params) # The returned cookie puts res. header ['set-cookies'] # returned html body puts res. body params = {} params ["name"] = 'Tom 'uri = URI. parse ("http: // uri") res = Net: HTTP. post_form (uri, params) # The returned cookie puts res. header ['set-cookies'] # returned html body puts res. body
3. HTTPS request
# Description: # Use https to send the express data to datasystem # input: # data-assembled expess data # output: # status information returned by datasystem # def self. senddatassl (url, data) url = url + data $ logger.info (url) begin uri = URI. parse (URI. escape (url) http = Net: HTTP. new (uri. host, uri. port) http. use_ssl = true if ($ logger! = Nil) $ logger.info ("URL parameter: # {URI. escape (url)}, FILE name: # {__ FILE __}, row # {__ LINE __} ") $ logger.info (" incoming data parameter: # {data. to_json}, FILE name: # {__ FILE __}, LINE # {__ LINE __} ") end request = Net: HTTP: Get. new (uri. request_uri) response = http. request (request) rescue => exception $ logger. error ("passed url address: # {url}, error! # {Exception. to_s}, FILE name: # {__ FILE __}, LINE # {__ LINE __} ") return nil end return response. body end
Articles you may be interested in:
- An asynchronous file download HttpServer instance implemented by ruby