如何制作Ruby';s RestClient gem尊重帖子上的内容类型?

如何制作Ruby';s RestClient gem尊重帖子上的内容类型?,ruby,rest-client,Ruby,Rest Client,例如,在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 UrlEnco

例如,在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
类UrlEncoded'application/x-www-form-urlencoded'})
结束
结束

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

您可能希望将json作为字符串而不是散列作为有效负载。例如,请执行以下操作:

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

如果查看payload.rb,它将显示如果有效负载是字符串,它将使用基类而不是urlcoded类。尝试一下,看看是否适合您。

我想补充一点,我的问题是在使用
RestClient::Request.execute
(与
RestClient.post
RestClient.get
相反)

问题在于我如何设置
:content\u 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"}'
)
res = RestClient::Request.execute(
  :method => :get,
  :url => url,
  :verify_ssl =>  false,
  :headers => { 
    :Authorization => "Bearer #{token}", 
    :content_type => :json,
    :accept => :json
  },
  :payload => '{"a":"b"}'
)
但实际上,您必须将它们放在
:标题中,如下所示:

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

对于
:post
请求,当
有效负载
哈希
时,
内容类型
标题将始终覆盖到
应用程序/x-www-form-urlencoded

可通过rest客户端(2.0.0)复制

解决方案

将哈希有效负载转换为json字符串

require 'json'

payload.to_json

rest客户端的repo中有一个问题:

我试图通过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_表单,但查询字符串更适合我的特定用例

虽然这不是常见的情况,并且完全取决于后端所期望的参数格式,但如果服务器期望url编码为POST正文,则在POST正文中传递查询字符串仍然是一个可行的选项。希望这能帮助一些人