2011-11-18 38 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