Ruby: How do I send a JSON POST request using Curb?

筅森魡賤 提交于 2019-12-03 12:21:15

问题


How can I set the request body of a CURB request to be my json string? I am trying to do a JSON POST request using Curb.

My code:

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

回答1:


The correct way of doing this is to simply add the content after the 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

This will set the json_string to be the request body.



来源:https://stackoverflow.com/questions/3851445/ruby-how-do-i-send-a-json-post-request-using-curb

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!