A simple example of sending a request based on an HTTP protocol in a Ruby program _ruby topic

Source: Internet
Author: User

1. Establish an HTTP connection (send request parameters by Get method)

Require "Open-uri"  
#如果有GET请求参数直接写在URI地址中  
uri = ' Http://uri '  
html_response = nil  
open (URI) do |http|  
Html_response = Http.read  
end  
puts Html_response  
require "Open-uri" 
#如果有GET请求参数直接写在URI地址中 
URI = ' Http://uri ' 
html_response = nil 
open (URI) do |http| 
Html_response = Http.read 
end 
puts Html_response 

2. Send request Parameters via post

params = {}  
params[' name ' = ' Tom '  
uri = uri.parse (' Http://uri ')  
res = Net::http.post_form
(URI, params)  
#返回的cookie  
puts res.header[' Set-cookie ']  
#返回的html body  
puts res.body  
= {} 
params["Name" = ' Tom ' 
uri = Uri.parse ("Http://uri") 
res = Net::http.post_form
(URI, params)  
#返回的cookie 
puts res.header[' Set-cookie '] 
#返回的html body 
puts Res.body 

3.HTTPS Request

# 
Description: 
#  send courier data to Datasystem, use HTTPS 
# input: # data  -assembled Expess's 
output:  # Datasystem return status Information 
# 
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 ("link address parameter: #{uri.escape (URL)}, FileName: #{__file__}, #{__line__} line") 
   $ Logger.info ("Incoming data parameter: #{data.to_json}, FileName: #{__file__}, #{__line__}") End 
  request = Net::http::get.new (Uri.request_uri) 
   
  Response = http.request (Request) 
 rescue =>exception 
  $logger. Error ("Delivery URL address is #{url}, error!#{exception.to_ s}, FileName: #{__file__}, #{__line__} line ") Return 
  Nil end 
 return 
 Response.body 

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.