Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/190.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 充当votable JSON put_Android_Ruby On Rails_Json_Http Put_Acts As Votable - Fatal编程技术网

Android 充当votable JSON put

Android 充当votable JSON put,android,ruby-on-rails,json,http-put,acts-as-votable,Android,Ruby On Rails,Json,Http Put,Acts As Votable,我有一个可以工作的rails应用程序,它是一个带有评论和向上/向下投票的博客。 移动组件供用户登录/注销、查看文章和向上/向下投票,而不是在此阶段添加文章或评论 我已经用简单的令牌auth gem实现了json登录,我可以获得文章和它们的上/下投票,这一切都正常,但我的问题是: 如何将json值发回?我的json代码在Android中工作,用于发布或推送json值,但如何构建正确的字符串来推送?要恢复的正确参数是什么 非常感谢 这来自rails服务器日志: html upvote的工作原理如下:

我有一个可以工作的rails应用程序,它是一个带有评论和向上/向下投票的博客。 移动组件供用户登录/注销、查看文章和向上/向下投票,而不是在此阶段添加文章或评论

我已经用简单的令牌auth gem实现了json登录,我可以获得文章和它们的上/下投票,这一切都正常,但我的问题是:

如何将json值发回?我的json代码在Android中工作,用于发布或推送json值,但如何构建正确的字符串来推送?要恢复的正确参数是什么

非常感谢

这来自rails服务器日志:

html upvote的工作原理如下:

Started PUT "/articles/5/like" for 137.147.172.125 at 2016-03-12 09:34:43 +0000
Cannot render console from 137.147.172.125! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by ArticlesController#upvote as HTML
  Parameters: {"authenticity_token"=>"4eC8xgC+1CBb51gKO7ZRzjL1BGOF6TYTnbqQcJ3evxvpmGcguYHBNYSn9v3LJMfoo3F29frntwzgyLoeI9oaLg==", "id"=>"5"}
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
  Article Load (0.1ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = ?  ORDER BY "articles"."created_at" DESC LIMIT 1  [["id", 5]]
   (0.3ms)  SELECT COUNT(*) FROM "votes" WHERE "votes"."votable_id" = ? AND "votes"."votable_type" = ? AND "votes"."voter_id" = ? AND "votes"."voter_type" = ? AND "votes"."vote_scope" IS NULL  [["votable_id", 5], ["votable_type", "Article"], ["voter_id", 1], ["voter_type", "User"]]
   (0.2ms)  begin transaction
  SQL (0.6ms)  INSERT INTO "votes" ("votable_id", "votable_type", "voter_id", "voter_type", "vote_flag", "vote_weight", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)  [["votable_id", 5], ["votable_type", "Article"], ["voter_id", 1], ["voter_type", "User"], ["vote_flag", "t"], ["vote_weight", 1], ["created_at", "2016-03-12 09:34:43.393685"], ["updated_at", "2016-03-12 09:34:43.393685"]]
   (11.4ms)  commit transaction
Redirected to https://completerubyonrailscourse-adam1st.c9users.io/articles/5
Completed 302 Found in 187ms (ActiveRecord: 13.2ms)
这就是我的android代码试图将json数据推回到rails服务器的时候:

Started PUT "/articles/5/like" for 49.199.131.149 at 2016-03-12 10:20:16 +0000
Cannot render console from 49.199.131.149! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by ArticlesController#upvote as JSON
  Parameters: {"votes"=>{"votable_id"=>"5", "votable_type"=>"Article", "voter_id"=>"1", "voter_type"=>"User", "vote_flag"=>"t", "vote_weight"=>"1", "created_at"=>"2016-03-12 21:20:13.679000", "updated_at"=>"2016-03-12 21:20:13.679000"}, "id"=>"5", "article"=>{}}
Can't verify CSRF token authenticity
Completed 401 Unauthorized in 2ms (ActiveRecord: 0.0ms)
那么,如何将其输入到json数据中呢?
参数:{“真实性令牌”=>“4eC8xgC+1CBB51GKO7ZLZJL1BGOF6TYTNBQQCJ3EVxVPMGCGUYHBNYSN9V3LJMFOO3F29FRNTWZGYLEI9OALG=”,“id”=>“5”}

从物品管理员处:

before_action :authenticate_user!, :except => [:index, :show]
before_filter :set_article, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
.
.
.    
def upvote
        @article.upvote_by current_user
        flash[:success] = "Successfully liked"
        respond_to do |format|
          format.html {redirect_to :back }
          format.json { render json: { count: @article.liked_count } }
        end
      end
      def downvote
        @article.downvote_by current_user
        flash[:success] = "Successfully disliked"
        respond_to do |format|
          format.html {redirect_to :back }
          format.json { render json: { count: @article.disliked_count } }
        end
      end
从与投票有关的show.html.erb:

<%= link_to like_article_path(@article), method: :put, class: 'voting' do %>
  <i class="fa fa-thumbs-up"></i>
    <%= @article.get_upvotes.size %>
<% end %>
<%= link_to dislike_article_path(@article), method: :put, class: 'voting' do %>
  <i class="fa fa-thumbs-down"></i>
    <%= @article.get_downvotes.size %>
<% end %>

将其添加到
应用程序\u controller.rb
文件中

 protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }

我去了简单令牌身份验证的git,看到了这个

身份验证方法2:请求头

您还可以使用请求头(在根据API进行身份验证时可能更简单):

X用户电子邮件alice@example.com

X-User-Token 1G8_s7P-V-4MGojaKD7a

因此,在进行投票之前,我将其放在标题中的投票任务中,它起了作用

private class VoteTask extends UrlJsonAsyncTask {
        public VoteTask(Context context) {
            super(context);
        }

        @Override
        protected JSONObject doInBackground(String... urls) {
            DefaultHttpClient webClient = new DefaultHttpClient();
            HttpPut put = new HttpPut(urls[0]);
            JSONObject holder = new JSONObject();
            JSONObject voteObj = new JSONObject();
            String response = null;
            JSONObject json = new JSONObject();

            try {
                try {
                    // setup the returned values in case
                    // something goes wrong
                    json.put("success", false);
                    json.put("info", "Something went wrong. Retry!");

                    //get stored values to prove the user is authorised
                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    String id = sharedPreferences.getString("userId", "default value");
                    String authToken = sharedPreferences.getString("AuthToken", "default value");
                    String email = sharedPreferences.getString("email", "default value");

                    voteObj.put("votable_id",articleId);
                    voteObj.put("votable_type", "Article");
                    voteObj.put("voter_id", id);
                    voteObj.put("voter_type", "User");
                    voteObj.put("vote_flag", voteFlag);
                    voteObj.put("vote_weight", "1");
                    holder.put("votes", voteObj);
                    holder.put("article", articleId);
                    StringEntity se = new StringEntity(holder.toString());
                    put.setEntity(se);

                    // setup the request headers
                    put.setHeader("Accept", "application/json");
                    put.setHeader("Content-Type", "application/json");
                    // add email and auth token to validate
                    put.setHeader("X-User-Email", email);
                    put.setHeader("X-User-Token", authToken);

                    //response = webClient.execute(put);
                    //json = new JSONObject(response);
                    response = String.valueOf(webClient.execute(put));
                    json = new JSONObject(response);


                } catch (HttpResponseException e) {
                    e.printStackTrace();
                    Log.e("ClientProtocol", "" + e);
                    json.put("info", "Email and/or password are invalid. Retry!");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("IO", "" + e);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("JSON", "" + e);
            }

            return json;
        }

谢谢,但我还是遇到了同样的问题:无法在2ms(ActiveRecord:0.0ms)内验证CSRF令牌的真实性。您能进一步解释一下吗?
private class VoteTask extends UrlJsonAsyncTask {
        public VoteTask(Context context) {
            super(context);
        }

        @Override
        protected JSONObject doInBackground(String... urls) {
            DefaultHttpClient webClient = new DefaultHttpClient();
            HttpPut put = new HttpPut(urls[0]);
            JSONObject holder = new JSONObject();
            JSONObject voteObj = new JSONObject();
            String response = null;
            JSONObject json = new JSONObject();

            try {
                try {
                    // setup the returned values in case
                    // something goes wrong
                    json.put("success", false);
                    json.put("info", "Something went wrong. Retry!");

                    //get stored values to prove the user is authorised
                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    String id = sharedPreferences.getString("userId", "default value");
                    String authToken = sharedPreferences.getString("AuthToken", "default value");
                    String email = sharedPreferences.getString("email", "default value");

                    voteObj.put("votable_id",articleId);
                    voteObj.put("votable_type", "Article");
                    voteObj.put("voter_id", id);
                    voteObj.put("voter_type", "User");
                    voteObj.put("vote_flag", voteFlag);
                    voteObj.put("vote_weight", "1");
                    holder.put("votes", voteObj);
                    holder.put("article", articleId);
                    StringEntity se = new StringEntity(holder.toString());
                    put.setEntity(se);

                    // setup the request headers
                    put.setHeader("Accept", "application/json");
                    put.setHeader("Content-Type", "application/json");
                    // add email and auth token to validate
                    put.setHeader("X-User-Email", email);
                    put.setHeader("X-User-Token", authToken);

                    //response = webClient.execute(put);
                    //json = new JSONObject(response);
                    response = String.valueOf(webClient.execute(put));
                    json = new JSONObject(response);


                } catch (HttpResponseException e) {
                    e.printStackTrace();
                    Log.e("ClientProtocol", "" + e);
                    json.put("info", "Email and/or password are invalid. Retry!");
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e("IO", "" + e);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.e("JSON", "" + e);
            }

            return json;
        }