2010-10-03 136 views
10

如何将CURB请求的请求正文设置为我的json字符串? 我正在尝试使用Curb做一个JSON POST请求。Ruby:我如何使用Curb发送JSON POST请求?

我的代码:

require 'rubygems' 
require 'curb' 
require 'json' 

myarray = {} 
myarray['key'] = 'value' 
json_string = myarray.to_json() 

c = Curl::Easy.http_post("https://example.com" 

     # how do I set json_string to be the request body? 

    ) do |curl| 
     curl.headers['Accept'] = 'application/json' 
     curl.headers['Content-Type'] = 'application/json' 
     curl.headers['Api-Version'] = '2.2' 
    end 

回答

39

这样做的正确方法是简单地添加URL后的内容:

c = Curl::Easy.http_post("https://example.com", json_string_goes_here 
    ) do |curl| 
     curl.headers['Accept'] = 'application/json' 
     curl.headers['Content-Type'] = 'application/json' 
     curl.headers['Api-Version'] = '2.2' 
    end 

这将设置json_string是请求主体。

+0

完美,也救了我。 – zachaysan 2011-03-10 19:32:14

+5

不错。类似这样的东西应该包含在Curb文档中。 – 2013-11-09 21:08:47

+2

我刚刚经历了一些我试图放入'json_string_goes_here'的数据。如果应用'JSON.pretty_generate(object)',使用ruby json库可以解决一些非转义字符的问题。 – hamitron 2015-12-15 01:01:38