我必须使用Rest-Client在Ruby中实现下面列出的curl POST请求。
我必须:
将params(不包含文件)发送为multipart/form-data
:
$ curl -X POST -i -H "Authorization: Bearer 2687787877876666686b213e92aa3ec7e1afeeb560000000001" \
https://api.somewhere.com/endpoint -F sku_id=608399
如何使用RestClient rubygem翻译curl请求?
阅读文档(多部分段落):https://github.com/rest-client/rest-client 我编码为:
@access_token = 2687787877876666686b213e92aa3ec7e1afeeb560000000001
url = 'https://api.somewhere.com/endpoint'
req = { authorization: "Bearer #{@access_token}"}
RestClient.post url, req, {:sku_id => 608399, :multipart => true}
但是我收到服务器错误;上面的Ruby代码是否正确?
非常感谢, 乔治
答案 0 :(得分:9)
由于我无法理解Dmitry所展示的示例,以下是创建上传图像的Multipart请求的示例:
response = RestClient.post 'https://yourhost.com/endpoint',
{:u_id => 123, :file => File.new('User/you/D/cat.png', 'rb'), :multipart => true},
{:auth_token => xyz5twblah, :cookies => {'_cookie_session_name' => cookie}}
答案 1 :(得分:2)
该代码对RestClient
实施无效。
在headers
之后应该payload
。
module RestClient
def self.post(url, payload, headers={}, &block)
...
end
end
<强>更新强>
@access_token
应为字符串"2687787877876666686b213e92aa3ec7e1afeeb560000000001"
然后
RestClient.log = 'stdout'
RestClient.post url, {:sku_id => 608399, :multipart => true}, req
并记录
RestClient.post "https://api.somewhere.com/endpoint", "--330686\r\nContent-Disposition: form-data; name=\"sku_id\"\r\n\r\n608399\r\n--330686--\r\n", "Accept"=>"*/*; q=0.5, application/xml", "Accept-Encoding"=>"gzip, deflate", "Authorization"=>"Bearer 2687787877876666686b213e92aa3ec7e1afeeb560000000001", "Content-Length"=>"79", "Content-Type"=>"multipart/form-data; boundary=330686"