如何在create action(post方法)中从客户端(android)到服务器端(ROR)获取数据?

时间:2013-06-11 10:50:30

标签: ruby-on-rails ruby ruby-on-rails-3 post

我正在从客户端向服务器端发送数据,从服务器端,它必须从客户端获取我发送的数据。

为此我们必须在def create action中使用post方法。

Serversudecide(ROR)

class PostsController < ApplicationController
respond_to :json, :xml

  before_filter :load

  def load
    if signed_in?
      @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      @my_post = current_user.posts.new
    end
    @posts = Post.paginate(page: params[:page],:per_page => 10)
    @post = Post.new
  end


  def index
    @posts = Post.all
    respond_with(@posts) do |format|
      format.json { render json: @post_names = {:post => @posts.as_json(:only=> :content)} }
    end
  end 

  def show
    if signed_in?
      @post = Post.find(params[:id])
      @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      current_user.vote_for(@post)
    else
    @post = Post.find(params[:id])
    Guest.find(1).vote_for(@post)
    end
    @posts = Post.paginate(page: params[:page],:per_page => 10)  
    @guest = Guest.new
    @user = User.new
    @users = User.paginate(page: params[:page],:per_page => 10)
  end

  def create 
    @post = Post.new(params[:post])
     respond_to do |format|
    if @post.save
      @posts = Post.paginate(page: params[:page],:per_page => 10)
      format.json { render json: @post, status: :created }

    else 
      @posts = Post.paginate(page: params[:page],:per_page => 10)
      format.json { render json: @post.errors, status: :unprocessable_entity }

    end
    @guest = Guest.new
    @users = User.paginate(page: params[:page],:per_page => 10)
 end
  end

  def my_prayer_create     
      @my_post = current_user.posts.new(params[:post])
      @post = Post.new(params[:post])
      @guest = Guest.new
      @user = User.new
      @users = User.paginate(page: params[:page],:per_page => 10)
      if @my_post.save
        flash[:notice] = "Prayer Successfully created."
        @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      else 
        flash[:notice] = "Error"
        @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      end
  end

  def edit
    if signed_in?    
    @my_post = current_user.posts.find(params[:id])
    else
    @post = Post.find(params[:id])
    end
  end

  def update
    if signed_in? 
      @my_post = current_user.posts.find(params[:id])
      if @my_post.update_attributes(params[:post])
        flash[:notice] = "Prayer Successfully updated."
        @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
      end
    else  
    @post = Post.find(params[:id])
    end
  end

  def destroy
    if signed_in? 
      @my_post = current_user.posts.find(params[:id])
      @users = User.paginate(page: params[:page],:per_page => 10)
      @guest = Guest.new
      @my_post.destroy
      flash[:notice] = "Prayer Successfully destroyed."
      @my_posts = current_user.posts.paginate(page: params[:page],:per_page => 10)
    end
  end
我在这里也提到了客户端代码。

public class HomeLayoutActivity extends Activity implements OnClickListener{

        private EditText value;
        private Button btn;
        private ProgressBar pb;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.home_layout);
            value=(EditText)findViewById(R.id.editText1);
            btn=(Button)findViewById(R.id.button1);
            pb=(ProgressBar)findViewById(R.id.progressBar1);
            pb.setVisibility(View.GONE);
            btn.setOnClickListener(this);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.home_layout, menu);
            return true;
        }

        public void onClick(View v) {
            // TODO Auto-generated method stub
                if(value.getText().toString().length()<1){

                    // out of range
                    Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
                }else{
                    pb.setVisibility(View.VISIBLE);
                    new MyAsyncTask().execute(value.getText().toString());  
                }


        } 

        private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

            @Override
            protected Double doInBackground(String... params) {
                // TODO Auto-generated method stub
                postData(params[0]);
                return null;
            }

            protected void onPostExecute(Double result){
                pb.setVisibility(View.GONE);
                Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
            }
            protected void onProgressUpdate(Integer... progress){
                pb.setProgress(progress[0]);
            }

            public void postData(String valueIWantToSend) {
                // Create a new HttpClient and Post Header
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://dry-brushlands-3645.herokuapp.com/posts");

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    nameValuePairs.add(new BasicNameValuePair("content", valueIWantToSend));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    //httppost.addHeader("Authorization","Basic "+authorization);
                    //httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
                    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
                    httppost.setHeader("Accept", "application/json");

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block


                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

如果我是对的,客户端提出的请求有点类似:

  • 来自客户端的post数据格式为:&content=valueIWantToSend
  • 在ROR应用程序中,在def create方法中,params[:content]将等于valueIWantToSend

在服务器端更改params[:post]params[:content]或在客户端更改contentpost(在try块内)< / p>