2011-11-18 174 views
11

例如,在RESTClient实现控制台:如何在后期制作Ruby的RestClient gem尊重content_type?

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

这不会发送应用程序/ 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导致内容类型得到尊重,但显然这不是真正的解决方案。有谁知道解决这个问题的正确方法?谢谢。

回答

20

您可能希望将json作为字符串作为您的有效负载而不是哈希。例如,做到:

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

如果你看看payload.rb,它表明,它将使用基本化酶,而不是url编码类,如果有效载荷是字符串。试试看看是否适合你。

+0

谢谢,这工作正常。 –

6

我想补充说,我的问题是当使用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"}' 
) 
6

事实

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

可重复使用rest-client(2.0.0)。

解决方案

转换哈希有效载荷JSON字符串。

require 'json' 

payload.to_json 

有一个在休息,客户的回购一ticket