0

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

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

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

服务器端代码。

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

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

我在这里也提到了我的客户端代码

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​​ on rails 中执行哪些代码

4

1 回答 1

0

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

查看类似问题如何使用 Android 发送 Json 数据: 如何使用 HTTPClient 在 JSON 中发送 POST 请求?

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

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

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

在此处输入图像描述

参数 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"}}
于 2013-06-10T10:11:54.073 回答