您的位置:首頁技術文章
文章詳情頁

ruby - Net::HTTP::POST 發送參數值為hash數組的方法

瀏覽:116日期:2024-08-10 09:08:37

問題描述

代碼如下(很常見的發送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 = trueendbegin request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data(data) res = http.request(request) if parsed[’code’] =1 parsed else nil endrescue puts ’communication failed’endend

這個方法發送類似{'name' => 'www.xxx.com', 'type'=>'download'}的參數,沒什么問題,但是現在有一個需求參數里有一個數組,數組的元素是map,類似{'ip'=>{'static.xxx.com'=>80,'img.xxx.com'=>23}},這個該怎么搞

問題解答

回答1:

可以使用Content-Type: application/json

body 放序列化的JSON

也可以使用to_query方法轉成url query string的形式

api: http://api.rubyonrails.org/classes/Object.html#method-i-to_query這是Rails里的方法

ruby - Net::HTTP::POST 發送參數值為hash數組的方法

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

to_json 轉成json放body

相關文章:
国产综合久久一区二区三区