Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom headers in volley request

I have a Volley Request code

RequestQueue queue = Volley.newRequestQueue(this);
String url =<My URL>;

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

How do I set a header called Authorization in this??

like image 483
John Oliver Avatar asked Oct 10 '15 12:10

John Oliver


2 Answers

Override getHeaders in request like:

 StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the first 500 characters of the response string.
                    mTextView.setText("Response is: "+ response.substring(0,500));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mTextView.setText("That didn't work!");
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params =  super.getHeaders();
            if(params==null)params = new HashMap<>();
            params.put("Authorization","Your authorization");
            //..add other headers
            return params;
        }
    };
like image 81
subhash Avatar answered Oct 03 '22 01:10

subhash


This here is a sample volley request showing how to add headers

private void call_api(final String url){

    if(!this.isFinishing() && getApplicationContext() != null){
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                resultsTextView.setVisibility(View.INVISIBLE);
                loader.setVisibility(View.VISIBLE);
            }
        });

        Log.e("APICALL", "\n token: " + url);


        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("APICALL", "\n response: " + response);
                        if(!FinalActivity.this.isFinishing()){
                            try {
                                JSONObject response_json_object = new JSONObject(response);

                                    JSONArray linkupsSuggestionsArray = response_json_object.getJSONObject("data").getJSONArray("package");
                                    final JSONObject k = linkupsSuggestionsArray.getJSONObject(0);
                                    final String result = k.getJSONArray("action").getJSONObject(0).getString("url");
                                    last_results_type = k.getString("type");
                                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {

                                            loader.setVisibility(View.INVISIBLE);
                                            resultsTextView.setText(result);
                                            resultsTextView.setVisibility(View.VISIBLE);
                                        }
                                    });
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "An unexpected error occurred.", Toast.LENGTH_LONG).show();
                                finish();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("APICALL", "\n error: " + error.getMessage());
                        Toast.makeText(getApplicationContext(), "Check your internet connection and try again", Toast.LENGTH_LONG).show();
                        finish();
                    }
                }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();
                headers.put("apiUser", "user");
                headers.put("apiKey", "key");
                headers.put("Accept", "application/json");
                //headers.put("Contenttype", "application/json");
                return headers;
            }

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<>();
                map.put("location", "10.12 12.32");
                return map;
            }

        };
        stringRequest.setShouldCache(false);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);
    }
}
like image 30
Dankyi Anno Kwaku Avatar answered Oct 03 '22 02:10

Dankyi Anno Kwaku