如何使用RestClient在post请求中发送数据

时间:2015-10-25 01:12:08

标签: ruby-on-rails ruby ruby-on-rails-4 curl rest-client

我试图使用RestClient Ruby gem模仿curl请求,到目前为止,我在尝试发送有效负载方面遇到了很多麻烦。我的卷曲请求看起来像这样

curl URL -X POST -u API_KEY -d '{"param_1": "1"}'

我一直试图用RestClient复制这个,使用类似的东西:

RestClient::Request.execute(method: :post, url: URL, user: API_KEY, payload: {"param_1" => "1"})

唉,这样做时我一直收到400 - Bad Requests错误。我是以错误的方式发送数据吗?我应该使用除有效载荷之外的东西吗?

3 个答案:

答案 0 :(得分:7)

变化:

payload: '{"param_1": "1"})'

要:

headers

另外,请指定RestClient::Request.execute(method: :post, url: 'your_url', user: 'API_KEY', payload: '{"param_1": "1"}', headers: {"Content-Type" => "application/json"} )

所以,它变成了:

{{1}}

答案 1 :(得分:3)

只需改变:

payload: {"param_1" => "1"}

要:

payload: {"param_1" => "1"}.to_json

那么,它就变成了:

RestClient::Request.execute(method: :post,
                            url: 'your_url',
                            user: 'API_KEY',
                            payload: {"param_1" => "1"}.to_json,
                            headers: {"Content-Type" => "application/json"}
                           )

答案 2 :(得分:1)

原来我必须添加一个参数来指定我的数据是JSON格式。正确答案是这样的: RestClient::Request.execute(method: :post, url: URL, user: API_KEY, payload: '{"param_1": "1"}', headers: {"Content-Type" => "application/json"})