标签:查询 请求 允许 ESS param ica encode 执行 会话
ruby中的NET::HTTP方法不支持持久连接,如果您执行许多HTTP请求,则不推荐它们;这里暂时先列出几个固定用法(用来还是有点不舒服的):
其中一,二不支持请求头设置(header取ruby默认值),只能用于基本的请求;三,四可以设置请求头;
NET::HTTP不能处理重定向和404 ;不支持会话保持
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
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
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
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
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
require ‘net/http‘ uri = URI(‘http://www.baidu.com‘) response = Net::HTTP.get_response(uri) puts "http版本:#{response.http_version}" #=> 1.1 puts "响应代码: #{response.code}" #=> 200 puts "响应信息:#{response.message}" #=> ok puts "uri:#{response.uri}" #=> http://www.baidu.com puts "解码信息:#{response.decode_content}" #=> true puts response.body #=> 响应体 response.header.each do |k,v| puts "#{k}:#{v}" end #=> 响应头
require ‘net/https‘ # 设置https http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE
标签:查询 请求 允许 ESS param ica encode 执行 会话
原文地址:https://www.cnblogs.com/wf0117/p/9000443.html