Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: HTTP Post to create new "Product" in a Ruby on Rails application

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.

like image 797
brodie31k Avatar asked Oct 15 '22 16:10

brodie31k


2 Answers

I added the following to my POST request and it worked like a charm.

httppost.addHeader("Content-Type","application/json");
like image 105
brodie31k Avatar answered Oct 19 '22 23:10

brodie31k


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

like image 26
Gdeglin Avatar answered Oct 20 '22 00:10

Gdeglin