使用RestClient而不是curl - 我该怎么做?

时间:2014-09-30 21:19:46

标签: ruby curl rest-client

我正在尝试使用RestClient执行以下当前在Curl中的以下内容:

curl -H "Content-Type: application/json" -X POST --data '{"contacts" : [1111],"text" : "Testing"}' https://api.sendhub.com/v1/messages/?username=NUMBER\&api_key=APIKEY

我没有在RestClient的文档中看到如何在上面执行等效的“--data”以及传递-H(Header)信息。

我尝试了以下内容:

url = "https://api.sendhub.com/v1/messages/?username=#{NUMBER}\&api_key=#{APIKEY}"
smspacket = "{'contacts':[#{contact_id}], 'text' : ' #{text} ' }"

RestClient.post url , smspacket, :content_type => 'application/json'

但这会给我一个错误请求错误。

1 个答案:

答案 0 :(得分:0)

我认为这可能已经很晚了,但是为了记录,我自己也在问自己的问题。

您的问题并非真正使用:to_json方法,因为它无论如何都会输出一个字符串。正文请求必须是字符串。 根据{{​​3}} json中的字符串必须使用"而不是'来定义,即使在javascript中我们主要使用这种方式来编写json。如果您根本不使用任何报价,那就相同。

这可能是您收到错误请求的原因。

pry(main)> {"test": "test"}.to_json
"{\"test\":\"test\"}"
pry(main)> JSON.parse(RestClient.post('http://httpbin.org/post', "{'test': 'test'}", {content_type: :json, accept: :json}).body)["json"]
nil
pry(main)> JSON.parse(RestClient.post('http://httpbin.org/post', '{test: "test"}', {content_type: :json, accept: :json}).body)["json"]
nil
pry(main)> JSON.parse(RestClient.post('http://httpbin.org/post', '{"test": "test"}', {content_type: :json, accept: :json}).body)["json"]
{"test"=>"test"}
相关问题