ruby net/http模块使用


ruby中的NET::HTTP方法不支持持久连接,如果您执行许多HTTP请求,则不推荐它们;这里暂时先列出几个固定用法(用来还是有点不舒服的):

其中一,二不支持请求头设置,只能用于基本的请求;三,四可以设置请求头;

NET::HTTP不能处理重定向和404 ;不支持会话保持

一. 基本GET请求get_response

require 'net/http'

# 基本GET请求
require 'net/http'
uri = URI('http://httpbin.org/get')
response = Net::HTTP.get_response(uri)
puts response.body


# 带参数的GET请求
require 'net/http'
uri = URI('http://httpbin.org/get?name=zhaofan&age=23')
response = Net::HTTP.get_response(uri)
puts response.body

# 如果我们想要在URL查询字符串传递数据,通常我们会通过httpbin.org/get?key=val方式传递
# URI模块允许使用 encode_www_form 方法,将一个HASH来进行转化,例子如下:
require 'net/http'
uri = URI('http://httpbin.org/get?')
data = {name:'zhaofan', age:23}
uri.query = URI.encode_www_form(data)
response = Net::HTTP.get_response(uri)
puts response.body

二.基本post请求post_form

require 'net/http'

# 基本POST请求
# 通过在发送post请求时添加一个params参数,这个params参数可以通过字典构造成;
# 该方法底层和get_response一样都是调用了response方法
uri = URI('http://httpbin.org/post')
params = {name:'zhaofan', age:23}
res = Net::HTTP.post_form(uri, params)
puts res.body

三.get固定用法

require 'net/http'

url = URI('http://httpbin.org/get?')
# 设置请求参数
params = {'name':'test'}
url.query = URI.encode_www_form(params)
http = Net::HTTP.new(url.host, url.port)
# 设置请求头
header = {'user-agent':'Chrome/61.0.3163.100'}

response = http.get(url, header)
puts response.body

四.post固定用法

  • application/json
    require 'net/http'
    require 'json'
    
    #application/json
    url = URI('http://httpbin.org/post')
    
    http = Net::HTTP.new(url.host, url.port)
    # 设置请求参数
    data = {'code':1, 'sex':'', 'id':1900, 'name': 'test'}.to_json
    # 设置请求头
    header = {'content-type':'application/json'}
    response = http.post(url, data, header)
    puts response.body
  • application/x-www-form-urlencoded
    require 'net/http'
    require 'json'
    
    #application/x-www-form-urlencoded
    url = URI('http://httpbin.org/post')
    http = Net::HTTP.new(url.host, url.port)
    #encodeURI参数
    data = URI.encode_www_form({'name':'test'})
    #设置请求头
    header = {'content-type':'application/x-www-form-urlencoded'}
    response = http.post(url, data,header)
    puts response.body

猜你喜欢

转载自www.cnblogs.com/wf0117/p/9000443.html