How to resend request with android volley when not authorized

丶灬走出姿态 提交于 2019-12-11 02:12:52

问题


In my android application I have to do some http request using android volley. If my request succeed everything's ok, the problem arise when I get an error and this error has status code 401. In this case I want to make some stuff and repeat the same request, same url and same parameters. Is there an official way to do that? If not, how can I get my params from error?

StringRequest req = new StringRequest(method, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response){
                    //VolleyLog.v("Response:%n %s", response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            NetworkResponse response = error.networkResponse;
            if(response.statusCode == 401){
                //make some stuff...
                //here i want to resend my request
            }
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            //get headers
        }

        @Override
        public Map<String, String> getParams() throws AuthFailureError {
            //get params
        }


    };

    // add the request object to the queue to be executed
    ApplicationController.getInstance().addToRequestQueue(req);

Any help would be appreciated.


回答1:


You can create the RetryPolicy to change default retry behavior, only specify timeout milliseconds, retry count arguments :

public class YourRequest extends StringRequest {
    public YourRequest(String url, Response.Listener<String> listener,
                       Response.ErrorListener errorListener) {
        super(url, listener, errorListener);
        setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
}

the another way is estimate the VolleyError, re-execute the same request again when if was TimeoutError instance :

public static void executeRequest() {
    RequestQueue.add(new YourRequest("http://your.url.com/", new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            if (error instanceof TimeoutError) {
                // note : may cause recursive invoke if always timeout.
                executeRequest();
            }
        }
    }));
}

Hope this will help you




回答2:


After modifying the request add the request in requestQueue. Do it in ErrorListener.



来源:https://stackoverflow.com/questions/31086386/how-to-resend-request-with-android-volley-when-not-authorized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!