Rails WDDX request | January 31, 2007-->
January 31, 2007I was asked how to get the body of an HTTP post request in a Rails controller. And with the most things in Rails it's very easy.
In Java you can get a ServletInputStream from the request object, in PHP there is $_SERVER['RAW_POST_DATA']. Pretty much like in the java version you can just ask the request object for raw_post in Rails.
# Simple RPC-Controller in Rails # request.raw_post contains the raw post data, that is # the data that is submitted in the http request body. # The example uses the wddx gem to return a simple WDDX response message # To us WDDX install the wddx gem ([sudo] gem install wddx) # and a require "wddx" statement # to config/environment.rb # app/controllers/rpc_controller.rb # This controller has a simple method "endpoint" # The body of the post request is written to the # log/#{environment}.log file. # The controller returns a WDDX XML message. class RpcController < ApplicationController # simple endpoint def endpoint if request.post? logger.debug request.raw_post render :xml => "Ok".to_wddx else render :xml => "Failure".to_wddx end end end
To test this controller you can use the following code to issue a post request.
#!/usr/bin/env ruby # # Created by Stefan Saasen on 2007-01-31. # Copyright (c) 2007. All rights reserved. require 'rubygems' require 'net/http' require 'wddx' begin http = Net::HTTP.new("localhost", 3000) response = http.post('/Rpc/endpoint', {"key" => "value", "another" => "value"}.to_wddx) puts response.body rescue SocketError => e # error handling end
