使用RestClient而不是卷曲 - 我该怎么做?
问题描述:
我试图使用RESTClient实现来做这是目前在卷曲如下:使用RestClient而不是卷曲 - 我该怎么做?
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(标题)信息。
我试过如下:
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'
但是,这给我一个错误请求错误。
答
我认为这可能是非常晚,但为了记录,并且因为我在附带自己的问题。
你的问题并不是使用或不使用:to_json
方法,因为它会输出一个字符串。正文请求必须是一个字符串。 根据http://json.org 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"}
确定要创建的网址是否正确?含义是否用NUMBER和APIKEY取代您所期望的值? – Max 2014-10-01 04:38:29
是的,数字是正确的,我想通了......硬编码的JSON格式是错误的。 – Angela 2014-10-02 19:19:43
其中一种可能性是RestClient添加了一些您的API不接受的标头。看看源代码,它似乎添加了一些默认标题:':{:accept =>'*/*; q = 0.5,application/xml',:accept_encoding =>'gzip,deflate'}'。你需要使用这个库吗?你可以使用其他许多库来制作http请求。 – Max 2014-10-03 02:35:53