Java: HTTP Post to create new “Product” in a Ruby

2019-02-14 16:20发布

问题:

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.

回答1:

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

httppost.addHeader("Content-Type","application/json");


回答2:

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



回答3:

To submit data in a POST request, you need to call httppost.setRequestBody(). This method takes an array of NameValuePairs with your data - consult the HTTP Client documentation for the correct syntax.