如何使用排球库GET方法在Android中发送授权标头

时间:2019-01-05 03:13:37

标签: android json android-volley

如何使用android中的凌空库发送GET方法的Authorization标头,请帮助我谢谢

  public void token(){
    SharedPreferences usuario = getActivity().getSharedPreferences(DataManager.SharedPreferences, Context.MODE_PRIVATE);
    String id = usuario.getString(DataManager.json_Id, "");
    final String token = usuario.getString(DataManager.json_Token,"");
    StringRequest request = new StringRequest(Request.Method.GET, urlReadUser, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (!response.equals(null)) {
                Log.e("Your Array Response", response);
            } else {
                Log.e("Your Array Response", "Data Null");
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            try {
                String responseBody = new String(volleyError.networkResponse.data, "utf-8");
                JSONObject jsonObject = new JSONObject(responseBody);
                //loadingData.dismiss();
                if (jsonObject.getInt(DataManager.json_Code) == 400) {
                   // onDialogErrorResponse();
                }

            } catch (JSONException e) {
                //Handle a malformed json response
                Log.d("Response", String.valueOf(e));
            } catch (UnsupportedEncodingException error) {

                Log.d("Response", String.valueOf(error));
            }
        }
    }) {

        //This is for Headers If You Needed
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("TOKEN", token);
            return params;
        }
    };
    request.setRetryPolicy(new DefaultRetryPolicy(
            10000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(request);
    DiskBasedCache cache = new 
    DiskBasedCache(getActivity().getCacheDir(), 500 * 1024 * 1024);
    requestQueue = new RequestQueue(cache, new BasicNetwork(new 
    HurlStack()));
    requestQueue.start();
}

我正在尝试通过GET方法向服务器发送数据请求,我必须发送令牌以便输入,但它返回一个错误,告诉我插入标头令牌的方式是错误的,希望他们能支持我。

1 个答案:

答案 0 :(得分:0)

授权标头通常以

形式发送
params.put("Authorization", "bearer " +token);

这里的承载是auth类型,它可以是Basic以及您的api要求。