Android pass Authentication Token in header using Volley

Asked

Viewed 137 times

0

I’m having trouble sending authentication token in header using Volley

This is my code

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Log.i("onActivityCreated: ", "token: ====> " + deliverymanEntitie.getTokenEntitie().getToken());

    RequestQueue queue = Volley.newRequestQueue(getContext());
    String url = RunfoxService.URL_GET_ALL_ORDERS_TO(deliverymanEntitie.getId());
    StringRequest stringRequest = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.i("onResponse: ", response);
        }

    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            try {
                String json = new String(error.networkResponse.data, "UTF-8");
                Log.e("onErrorResponse: ", json);
                Log.e("onErrorResponse: ", error.networkResponse.headers.toString());


            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-type", "application/application/json; charset=UTF-8");
            headers.put("Accept", "application/json; charset=UTF-8");
            headers.put("api_token", deliverymanEntitie.getTokenEntitie().getToken());

            Log.i("getHeaders: ", headers.toString());

            return headers;
        }
    };

    queue.add(stringRequest);

}

In the code above we have all the request performed, here are my logs

error log of my api

E/onErrorResponse:: {"message":"Token de acesso n\u00e3o informado"}

Testing with Postman the same request and also in the header the token I can get the json result correctly.

Apparently I’m not able to inform the token in the headers, someone knows tell me where I’m going wrong?

  • From your description, the only thing that could be happening is deliverymanEntitie.getTokenEntitie().getToken() be returning null or empty. Already put some breakpoints ai, debugged and saw that actually has come a token of this function?

1 answer

1


I solved my problem by simply removing the "_" from the api_token and staying like this:

headers.put("apitoken", deliverymanEntitie.getTokenEntitie().getToken());

that way I managed to pass and receive in my API, I don’t know sinking on the reason but it worked for me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.