Java:HTTP Post在Ruby on Rails应用程序中创建新的“Product”

在Android上使用Apache HttpClient,如何使用HttpPost将数据发送到RESTfull Ruby on Rails应用程序。

这是我的控制器:

# 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 

这是我的Java代码。 我应该在URL名称中传递数据,还是必须在其他地方设置它? (也许是httpost.setEntity?)最后我会使用JSON但是现在我只想得到它所以我实际上可以在Rails中调用“create”方法。 Rails正在获取POST,但从不在“create”方法中执行任何代码

  HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.0.100:3000/products/new"); HttpResponse response = httpclient.execute(httppost); 

我很困惑,如果有人能指出我正确的方向,我会很感激。

我在POST请求中添加了以下内容,它就像一个魅力。

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

Rails没有在Create方法中执行任何代码,因为您正在向“New”方法发出请求。

通常,New方法用于呈现用户随后提交给create方法的HTML表单。 对于Web服务,不需要此方法。

请使用urlhttp://192.168.0.100:3000/products (不带/新)。 默认情况下,rails会通过查看请求类型并查看它是POST请求,将此请求路由到Create方法。

这假设您已正确设置Products作为路由中的RESTful资源。 否则,您将需要使用http://192.168.0.100:3000/products/create 。 以下是RESTful资源和路由的API文档: http : //api.rubyonrails.org/classes/ActionController/Resources.html

要在POST请求中提交数据,您需要调用httppost.setRequestBody() 。 此方法使用您的数据获取NameValuePair数组 – 请参阅HTTP客户端文档以获取正确的语法。