Using the Apache HttpClient on android, how do I send data to a RESTfull Ruby on Rails app using HttpPost.
This is my Controller:
# POST /products
def create
@product = Product.new(params[:product])
respond_to do |format|
if @product.save
flash[:notice] = 'Product was successfully created.'
format.html { redirect_to(@product) }
format.xml { render :xml => @product, :status => :created, :location => @product }
else
format.html { render :action => "new" }
format.xml { render :xml => @product.errors, :status => :unprocessable_entity }
end
end
end
And this is my Java Code. Should I be passing the data in the URL name, or do I have to set it somewhere else? (httpost.setEntity perhaps?) Eventually I will be using JSON but for now I just want to get it so I can actually call the "create" method in Rails. Rails is getting the POST but never executes any code in the "create" method
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.100:3000/products/new");
HttpResponse response = httpclient.execute(httppost);
I am quite stuck and would appreciate if someone could point me in the right direction.
I added the following to my POST request and it worked like a charm.
httppost.addHeader("Content-Type","application/json");
Rails is not executing any code in the Create method because you are making a request to the "New" method.
Typically the New method is used to render an HTML form that the user then submits to the create method. For a web service this method is not needed.
Use the url http://192.168.0.100:3000/products
(without /new) instead. By default, rails will route this request to the Create method by looking at the request type and seeing that it is a POST request.
This assumes you have correctly set up Products to be a RESTful resource in your routes. Otherwise you will need to use http://192.168.0.100:3000/products/create
. Here is the API doc for RESTful resources and routes: http://api.rubyonrails.org/classes/ActionController/Resources.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With