ruby add data to POST Request body as Formdata

时间:2018-06-04 17:38:15

标签: ruby-on-rails ruby request http-post

I am working on an implementation where I need to call a POST web-service which expects body as form-data. So when I test from PostMan app I select 'Body' then 'form-data' and enter my two keys and their values to make the call.
This can be done in Java using jersey-media-multipart library and then doing something like this MultiPart mp = new MultiPart(); FormDataBodyPart my_form_data1 = new FormDataBodyPart("my_key1", inputStream1, inputType1);
mp.addBodyPart(my_form_data1)
.

However from my first Ruby on Rails project unsure how this can be accomplished.
Any ideas?

1 个答案:

答案 0 :(得分:0)

Ruby类Net :: HTTP可以发布表单数据。文档在这里https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html

例如

uri = URI('http://www.example.com/search.cgi')
res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50')
puts res.body

如果您使用的是PostMan,您可以将命令复制为curl并使用Ruby代码重新创建它。例如,如果从PostMan

收到以下curl命令

卷曲-X POST \   https://example.com/somthing/somthing/hay-now \   -H'Cache-Control:no-cache'\   -H'内容类型:application / x-www-form-urlencoded'\   -H'Postman-Token:cabfef34-17b1-43b5-bb95-ac7a9ec35bcb'\   -d test = testvalue``

您可以像这样重新创建curl命令。

require 'net/http'    

uri = URI('https://example.com/somthing/somthing/hay-now')
    request = Net::HTTP::Post.new(uri)
    request. content_type = 'application/x-www-form-urlencoded'
    request.set_form_data('test' => 'testValue')
    Net::HTTP.start(uri.host, uri.port) do |http|
      response = http.request(request)
    end

请注意,这只是一个例子。