ruby - Net::HTTP::POST 发送参数值为hash数组的方法
大家讲道理
大家讲道理 2017-04-24 09:11:11
0
1
829

代码如下(很常见的发送post的方法):

def access_api(path, data) uri = URI(path) http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.use_ssl = true end begin request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data(data) res = http.request(request) if parsed['code'] =1 parsed else nil end rescue puts 'communication failed' end end

这个方法发送类似{"name" => "www.xxx.com", "type"=>"download"}的参数,没什么问题,但是现在有一个需求参数里有一个数组,数组的元素是map,类似{"ip"=>{"static.xxx.com"=>80,"img.xxx.com"=>23}},这个该怎么搞

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all (1)
黄舟

Can be usedContent-Type: application/json

body puts serialized JSON

You can also use the to_query method to convert it into the form of url query string

api: http://api.rubyonrails.org/classes/Object.html#method-i-to_query
This is the method in Rails

{:token=>"6df95c86c2be8f3d44eaa2da04f173ba", :name=>"www.xxxx.com", :type=>"download", :ip=>[{:"static.xxx.com"=>80}, {:"img.xxx.com"=>80}]}

to_json Convert to json and put the body

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!