【问题标题】:Android Volley Request with OAuth2 Authorization带有 OAuth2 授权的 Android Volley 请求
【发布时间】:2016-11-07 11:37:13
【问题描述】:

我需要调用一个 REST API 来简单地更新数据库中某个字段的值。为此,我使用以下 Volley 请求,但它返回意外响应代码 401(未经授权),似乎 OAuth2 授权的标头被忽略。我检查了访问令牌值,它是正确的。我的错误是什么?

private void sendRegistrationTokenToServer(final String token) {
         // user ID taken from SharedPreferences
         final String id = Integer.toString(SharedPrefManager.getInstance(this).getUserId());

         StringRequest stringRequest = new StringRequest
            (
             Request.Method.PUT,
             Constants.URL_GCM_TOKEN+"/"+ Utils.base64Encode(id),

             new Response.Listener<String>()
                {
                 @Override
                 public void onResponse(String s)
                    {
                     Intent registrationComplete = new Intent(REGISTRATION_TOKEN_SENT);
                     LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(registrationComplete);
                    }
                },

             new Response.ErrorListener()
                {
                 @Override
                 public void onErrorResponse(VolleyError volleyError)
                    {
                     Toast.makeText(getBaseContext(), "Unexpected error occurred when saving the GCM token for push notifications", Toast.LENGTH_LONG).show();
                    }
                })
            {
             @Override
             protected Map<String, String> getParams() throws AuthFailureError
                {
                 Map<String, String> params = new HashMap<>();

                 params.put("gcm_token", token);

                 return params;
                }


             @Override
             public Map<String, String> getHeaders() throws AuthFailureError
                {
                 Map<String, String> headers = new HashMap<String, String>();

                 headers.put("Content-Type", "application/json");

                 String bearer = "Bearer ".concat(SharedPrefManager.getInstance(getBaseContext()).getUserAccessToken());

                 headers.put("Authorization", bearer);

                 return headers;
                }
            };

         App.getInstance().addToRequestQueue(stringRequest);
        }

【问题讨论】:

    标签: android oauth-2.0 request android-volley


    【解决方案1】:

    我自己回答,以防有人需要知道解决方案:) 出于某种动机,服务器策略删除了 Authorization 标头,因此我必须提供一个不同的自定义标头,名为 X-Authorization-Copy,其值与 Authorization 一个(“Bearer ”),我不得不修改服务器代码以管理在 Authorization 标头中找不到的情况请求。因此,服务器检查是否存在其他自定义 X-Authorization-Copy 标头,并从中获取授权数据。 此外,Content-Type header 必须是 x-www-form-urlencoded,而不是 application/json,否则会报错。 现在可以了。

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 2018-03-11
      • 2015-11-28
      • 2020-05-11
      • 2022-11-14
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多