2011-06-22 51 views
4

我是新來的Ruby on Rails的,並試圖簡單地測試,如果我可以簡單地做類似下面從我的控制器:使用Ruby on Rails的發送HTTP請求

捲曲-v -H「內容類型: application/json「-X GET -d」{bbrequest:BBTest reqid:44 data:{name:「test」}}「http://localhost:8099

在您的HTTP請求中發送JSON的最佳做法是什麼?

感謝

回答

17

你可以做這樣的事情:

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以獲取更多信息。

+0

當我使用以下命令向服務器發送HTTP請求時:curl -v -H「Content-Type:application/json」-X GET -d「{」bbrequest「:」BBTest「,」reqid「:」44「, 「data」:{「name」:「test」}}「http:// localhost:8099 ...我的服務器將JSON數據視爲」{bbrequest:BBTest,reqid:44,data:{name:test}}「 當我使用您建議的代碼發送請求時,它將其視爲「{\」bbrequest \「:\」BBTest \「,\」reqid \「:\」44 \「,\」data \「:{ \「name \」:\「 測試\」}}「和服務器無法解析它,也許有一些額外的選項,我需要設置從紅寶石發送請求以排除這些額外的字符?你能幫忙嗎? 在此先感謝。 –

+0

這是因爲將散列轉換爲json格式。你將不得不解碼它。例如。 '{「a」=>「b」}。to_json'給你'「{\」a \「:\」b \「}」'和'ActiveSupport :: JSON.decode(「{\」a \「: \「b \」}「)'給你'{」a「=>」b「}'。 – David