如何使用Curb发送JSON

如何使用Curb发送JSON

本文介绍了Ruby:如何使用Curb发送JSON POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将CURB请求的请求主体设置为我的json字符串?我正在尝试使用Curb进行JSON POST请求.

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.

我的代码:

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

推荐答案

正确的方法是在URL后面简单地添加内容:

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

这会将json_string设置为请求正文.

This will set the json_string to be the request body.

这篇关于Ruby:如何使用Curb发送JSON POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:05