如何使Ruby的RestClient gem在post时遵守content_type?

17

例如,在RestClient控制台中:

RestClient.post 'http://localhost:5001', {:a => 'b'}, :content_type => 'application/json'
这不会发送application/json作为内容类型。 相反,我看到:
Content-Type: application/x-www-form-urlencoded

我能够追踪到更改是在restclient/payload.rb中进行的:

  class UrlEncoded < Base
  ...

  def headers
    super.merge({'Content-Type' => 'application/x-www-form-urlencoded'})
  end
end

将super.merge替换为super会使内容类型得到尊重,但显然这不是一个真正的解决方案。有人知道正确的修复方式吗?谢谢。

4个回答

24

你可能想将JSON作为字符串而不是哈希表放入负载中。例如:

RestClient.post 'http://localhost:5001','{"a":"b"}',:content_type => 'application/json'

如果你查看payload.rb文件,会发现当负载为字符串时,它会使用Base类而不是UrlEncoded类。尝试一下并看看是否能解决你的问题。


17

事实:

对于: post请求,当payload是一个Hash时,Content-Type头将始终被覆盖为application/x-www-form-urlencoded

使用rest-client(2.0.0)可重现此问题。

解决方案:

将哈希负载转换为JSON字符串。

require 'json'

payload.to_json

rest-client的存储库中有一个票据


11

我想补充说明一下,我的问题出现在使用RestClient::Request.execute时 (而不是RestClient.postRestClient.get)。

问题出在我设置:content_type:accept的方式上。从我看到的例子中,它们应该像这样成为顶级选项:

res = RestClient::Request.execute(
  :method => :get,
  :url => url,
  :verify_ssl =>  false,
  :content_type => :json,
  :accept => :json,
  :headers => { 
    :Authorization => "Bearer #{token}", 
  },
  :payload => '{"a":"b"}'
)

但实际上,您必须将它们放在:headers中,就像这样:

res = RestClient::Request.execute(
  :method => :get,
  :url => url,
  :verify_ssl =>  false,
  :headers => { 
    :Authorization => "Bearer #{token}", 
    :content_type => :json,
    :accept => :json
  },
  :payload => '{"a":"b"}'
)

0
我试图以表单数据格式通过POST方式提交用户名、密码、CSRF令牌和身份验证cookie。将有效载荷转换为JSON并显式设置内容类型标头都没有帮助。最终我将有效载荷作为查询字符串传递,并删除了其转换为JSON的步骤。
RestClient::Request.execute(
  method: :post, 
  url: 'http://app_url/login.do',
  payload: "username=username&password=password&_csrf=token",
  headers: {'X-XSRF-TOKEN' => 'token'},
  cookies: {'XSRF-TOKEN' =>  cookie_object}
)

另一个选择也可以使用encode_www_form,但对于我的特定用例来说,查询字符串的效果更好。

虽然这不是常见情况,并且一切都取决于后端期望的参数格式,但如果服务器期望将URL编码作为POST主体,则在POST主体中传递查询字符串仍然是可行的选项。希望这可能会帮助某些人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接