如何让Ruby的RestClient gem在post上尊重content_type?
例如,在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 'application/x-www-form-urlencoded'}) end end
用super替换super.merge会导致内容类型得到尊重,但显然这不是一个真正的解决方案。 有谁知道解决这个问题的正确方法? 谢谢。
您可能希望将json作为字符串作为有效负载而不是散列。 例如,做:
RestClient.post 'http://localhost:5001','{"a":"b"}',:content_type => 'application/json'
如果你查看payload.rb,它会显示如果有效负载是字符串,它将使用Base clase而不是UrlEncoded类。 试试看,看看那对你有用吗。
事实 :
对于:post
请求,当payload
是Hash
, Content-Type
头将始终被覆盖到application/x-www-form-urlencoded
。
可以与rest-client一起重现(2.0.0)。
方案 :
将哈希有效负载转换为json字符串。
require 'json' payload.to_json
在rest-client的回购中有一张票 :
我想补充说我的问题是在使用RestClient::Request.execute
(与RestClient.post
或RestClient.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
像这样的:headers
:
res = RestClient::Request.execute( :method => :get, :url => url, :verify_ssl => false, :headers => { :Authorization => "Bearer #{token}", :content_type => :json, :accept => :json }, :payload => '{"a":"b"}' )