ruby - Net::HTTP::POST 發送參數值為hash數組的方法
問題描述
代碼如下(很常見的發送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里的方法
{:token=>'6df95c86c2be8f3d44eaa2da04f173ba', :name=>'www.xxxx.com', :type=>'download', :ip=>[{:'static.xxx.com'=>80}, {:'img.xxx.com'=>80}]}
to_json 轉成json放body
相關文章:
1. angular.js - webpack怎么做到liveload?2. ruby - 為什么無法啟動Rails呢?3. Android控件和傳值跳轉問題4. mysql取模分表與分表5. mysql - Access denied for user ’ODBC’@’localhost’ (using password: NO)6. css3 - <img>圓角屬性在手機瀏覽器顯示不全7. javascript - async/await 與 forEach 問題8. html5 - cordova keyboard插件調取到的鍵盤是數字鍵盤(求解)9. angular.js - angularjs用websocket做聊天功能發送不出去消息10. a標簽跨域下載文件能否重命名?
