在ruby on rails上如何从客户端获取数据(android)

时间:2013-06-10 08:18:00

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

Android作为客户端,我将数据从客户端发送到服务器端。作为服务器端的rails,如何使用post方法从客户端获取数据。

我想从客户端到服务器端获取数据以显示。 对于客户端,我有代码如何将数据发送到服务器端,但在服务器中我不知道如何获取数据。

仅使用服务器端,我们必须创建url,并且我们必须在客户端代码中使用该URL来发送数据。

serversidecode。

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])
    if @post.save
      @posts = Post.paginate(page: params[:page],:per_page => 10)
    else 
      @posts = Post.paginate(page: params[:page],:per_page => 10)
    end
    @guest = Guest.new
    @users = User.paginate(page: params[:page],:per_page => 10)

  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

这是服务器端,如何在这里从客户端获取数据。

Myclientside代码我也在这里提到

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://localhost:3000/posts/create_a_post");

                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/json");
                    httppost.addHeader("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


                }
            }
        }
    }

如何从客户端获取数据,我必须在轨道上的ruby中执行哪些代码

1 个答案:

答案 0 :(得分:0)

您不会将Json发送到服务器。

查看类似的问题如何使用Android发送Json数据: How to send POST request in JSON using HTTPClient?

如果您的Json是正确的,您可以使用params方法在Rails中访问您的数据,在正常的Web请求或Android客户端请求之间访问params没有区别。

您无需更改Rails代码。使用Http-Client发出测试请求。

我使用HttpRequester制作了一个示例请求的屏幕截图:

enter image description here

params post [name]和post [user_id]仅示例,将其替换为您的属性。

发送请求后,您的开发服务器控制台应具有以下输出:

Started POST "/posts" for 127.0.0.1 at 2013-06-10 13:31:01 +0200
Processing by PostsController#create as HTML
  Parameters: {"post"=>{"name"=>"name", "user_id"=>"5"}}