在Rails上使用ruby发送HTTP请求 [英] Sending HTTP request using ruby on rails
本文介绍了在Rails上使用ruby发送HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚接触ruby并尝试测试是否可以通过控制器执行以下操作:
I'm new to ruby on rails and trying to test if I could do something like the below from my controller:
curl -v -H "Content-Type: application/json" -X GET -d "{bbrequest:BBTest reqid:44 data:{name: "test"}}" http://localhost:8099
在HTTP请求中发送JSON的最佳做法是什么?
And what is the best practice to send JSON in your HTTP requests?
推荐答案
您可以执行以下操作:
def post_test
require 'net/http'
require 'json'
@host = 'localhost'
@port = '8099'
@path = "/posts"
@body ={
"bbrequest" => "BBTest",
"reqid" => "44",
"data" => {"name" => "test"}
}.to_json
request = Net::HTTP::Post.new(@path, initheader = {'Content-Type' =>'application/json'})
request.body = @body
response = Net::HTTP.new(@host, @port).start {|http| http.request(request) }
puts "Response #{response.code} #{response.message}: #{response.body}"
end
查找 Net :: HTTP 以获得更多信息.
这篇关于在Rails上使用ruby发送HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文