簡體   English   中英

具有OAuth2授權的Android Volley請求

[英]Android Volley Request with OAuth2 Authorization

我需要調用一個REST API,該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);
        }

我回答自己,以防有人需要知道解決方案:)為了某種動機,服務器策略刪除了Authorization標頭,因此我必須提供一個不同的自定義標頭,名為X-Authorization-Copy ,其值與Authorization相同。一個(“ 承載 ”),並且我不得不修改服務器代碼,以管理在請求中找不到Authorization標頭的情況。 因此,服務器檢查是否存在其他自定義X-Authorization-Copy標頭,並從中獲取授權數據。 此外,Content-Type標頭必須為x-www-form-urlencoded,而不是application / json,否則會產生錯誤。 現在可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM