A simple example of sending HTTP-based requests in Ruby programs.

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.