【问题标题】:Rest-Client: how to post multipart/form-data?Rest-Client:如何发布 multipart/form-data?
【发布时间】:2015-07-08 06:05:13
【问题描述】:

我必须使用 Rest-Client 在 Ruby 中实现下面列出的 curl POST 请求。

我必须:

  • 在标头中发送参数;
  • 发送参数(不包含文件)为multipart/form-data:

    $ curl -X POST -i -H "Authorization: Bearer 2687787877876666686b213e92aa3ec7e1afeeb560000000001" \
        https://api.somewhere.com/endpoint -F sku_id=608399
    

如何使用 RestClient ruby​​gem 翻译 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 代码正确吗?

非常感谢, 乔治

【问题讨论】:

  • 您可以尝试将标头用作哈希:{ :authorization => "Bearer #{@access_token}"} 吗?此外,如果它仍然抛出错误,请在此处分享错误跟踪,以便我们查看发生了什么。
  • 嗨,Xammy,我得到了一个 http 状态代码 401,但是,正如服务器端人员所证实的,这不是访问令牌错误的问题(哈希运行 Smoothley 和其他 api 端点)

标签: ruby curl http-headers multipartform-data rest-client


【解决方案1】:

由于我无法理解 Dmitry 展示的示例,以下是创建多部分请求以上传图像的示例:

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}}

【讨论】:

  • 谢谢。我必须在一个 POST 中同时发送 xml 和文件,而您的示例对我有用。
【解决方案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"

【讨论】:

  • 哦,你是对的,Dmitry,所以RestClient.post url, {:sku_id => 608399, :multipart => true}, req 可能是最好的 :-) 所以问题是:可以像这里的代码一样将有效负载作为 multipart/form-data 提交吗?
  • 谢谢,已解决!正如您所写,顺便说一句,是的:访问令牌是一个字符串,我的错字:-( 只是一个小注:RestClient.log = 'stdout' 对我不起作用,但这是另一个故事。感谢您的耐心
  • 当然。也许你使用不同版本的rest-client,从这里得到它github.com/rest-client/rest-client/blob/master/lib/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
  • 1970-01-01
相关资源
最近更新 更多