nicklbaert
nicklbaert

Reputation: 57

How do I add a custom authorization header to my JSON request?

I need to send a request that authorizes the user by providing a bearer token. How can i add a header to my request that contains this bearer token.

This is what my request looks like:

JsonObjectRequest jsonObjReq2 = new JsonObjectRequest(Request.Method.POST, personUrl, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //something } });

Upvotes: 0

Views: 424

Answers (1)

Sabiha Mahboob Khan
Sabiha Mahboob Khan

Reputation: 36

You can override one more method, which is getHeaders().

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> params = new HashMap<String, String>();
    params.put("Content-Type", "application/json");
    params.put("Accept-Language", "en"); //add as many headers as you want
    return params;
}

Little tip here is, stop using volley and use Retrofit Instead. Its much better, clean and easy. You can check this course to learn retrofit in detail: Android Retrofit Tutorial.

Upvotes: 1

Related Questions