Ruby:如何使用Curb发送JSON POST请求?

Mar*_*rco 10 ruby post curb

如何将CURB请求的请求主体设置为我的json字符串?我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 40

这样做的正确方法是简单地在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
Run Code Online (Sandbox Code Playgroud)

这会将json_string设置为请求主体.

  • 尼斯.这样的东西应该包含在Curb文档中. (8认同)
  • 我刚刚对`json_string_goes_here`中的一些数据感到悲痛.如果你应用`JSON.pretty_generate(object)`,使用ruby json库可以解决未转义字符的一些问题. (3认同)