How to resend request with android volley when not

2019-07-20 04:40发布

问题:

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.