2010-06-08 65 views
4

我想通過RestClient ruby​​ API將JSON數據發送到Sinatra應用程序。使用RestClient和Sinatra發送和接收JSON

在客戶端(client.rb)(使用RESTClient實現API)

response = RestClient.post 'http://localhost:4567/solve', jdata, :content_type => :json, :accept => :json 

在服務器(西納特拉)

require "rubygems" 
require "sinatra" 


post '/solve/:data' do 

    jdata = params[:data] 

    for_json = JSON.parse(jdata) 

end 

我收到以下錯誤

/Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/abstract_response.rb:53:in `return!': Resource Not Found (RestClient::ResourceNotFound) 
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:193:in `process_result' 
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:142:in `transmit' 
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/net/http.rb:543:in `start' 
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:139:in `transmit' 
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:56:in `execute' 
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:31:in `execute' 
    from /Library/Ruby/Gems/1.8/gems/rest-client-1.5.1/lib/restclient.rb:72:in `post' 
    from client.rb:52 

所有我想要的是發送JSON數據並使用RestClient和Sinatra接收JSON數據。但無論我嘗試什麼,我都會收到上述錯誤。我堅持了3個小時。請幫助

回答

14

您的sinatra應用程序與http://localhost:4567/solve URL不匹配,所以它會從您的服務器返回404。

您需要通過例如改變你的末日應用:

require "rubygems" 
require "sinatra" 


post '/solve/?' do 
    jdata = params[:data] 
    for_json = JSON.parse(jdata) 
end 

你有一個問題,你的RESTClient實現的要求了。您需要定義jdata的參數名稱。

response = RestClient.post 'http://localhost:4567/solve', {:data => jdata}, {:content_type => :json, :accept => :json} 
+0

我用你的代碼做了。但我仍然得到這個概率 – Anand 2010-06-08 12:39:00

+0

我沒有重新啓動我的sintara服務器..多數民衆贊成的概率..;)你的代碼工作像甜 – Anand 2010-06-08 13:57:09

0

試試這個:

jdata = {:key => 'I am a value'}.to_json  
response = RestClient.post 'http://localhost:4567/solve', :data => jdata, :content_type => :json, :accept => :json 

然後試試這個:

post '/solve' do 
    jdata = JSON.parse(params[:data]) 
    puts jdata 
end 

我沒有測試它,但也許你應該值發送JSON數據,而不是一個關鍵。有可能你的數據如下所示:{:key =>'我是一個值'} => nil。你的數據不一定必須在URL中。你不需要/解決/:數據網址。 POST值不會在URL 調試你在你的路線收到什麼好辦法來送是打印PARAMS:

puts params 

希望這有助於!