Send and Receive JSON using RestClient and Sinatra
I am trying to send a JSON data to a Sinatra app by RestClient ruby API.
At client(client.rb) (using RestClient API)
response = RestClient.post 'http://localhost:4567/solve', jdata, :content_t开发者_运维知识库ype => :json, :accept => :json
At server (Sinatra)
require "rubygems"
require "sinatra"
post '/solve/:data' do
jdata = params[:data]
for_json = JSON.parse(jdata)
end
I get the following error
/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
All I want is to send JSON data and receive a JSON data back using RestClient and Sinatra..but whatever I try, I get the above error. I m stuck with this for 3 hours. Please help
Your sinatra app, don't match with http://localhost:4567/solve URL, so it's return a 404 from your server.
You need change your sinatra app by example :
require "rubygems"
require "sinatra"
post '/solve/?' do
jdata = params[:data]
for_json = JSON.parse(jdata)
end
You have a problem with your RestClient request too. You need define the params name of jdata.
response = RestClient.post 'http://localhost:4567/solve', {:data => jdata}, {:content_type => :json, :accept => :json}
Try this:
jdata = {:key => 'I am a value'}.to_json
response = RestClient.post 'http://localhost:4567/solve', :data => jdata, :content_type => :json, :accept => :json
And then try this:
post '/solve' do
jdata = JSON.parse(params[:data])
puts jdata
end
I didn't test it but maybe you should send the json data as value rather than a key. Is is possible that you data looks like this: {:key => 'I am a value'} => nil. Your data does not necessary has to be in url at all. You don't need /solve/:data url. POST values are not to be send in url A good way to debug what you receive in your route is to print the params:
puts params
Hope this helps!
精彩评论