Android Volley:在哪里添加重试策略和超时?

时间:2015-12-13 09:49:59

标签: java android android-volley

请,我不知道添加/编辑超时和重试策略的位置。 基本上我会有3秒。超时,并将rety策略设置为零。

我正在使用网络上找到的模式。

Controller.java

public class Controller extends Application {

    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";

    /**
     * Global request queue for Volley
     */
    private RequestQueue mRequestQueue;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    /**
     * Adds the specified request to the global queue, if tag is specified
     * then it is used else Default TAG is used.
     *
     * @param req
     * @param tag
     */
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        VolleyLog.d("Adding request to queue: %s", req.getUrl());

        getRequestQueue().add(req);
    }

    /**
     * Adds the specified request to the global queue using the Default TAG.
     *
     * @param req
     * @param tag
     */
    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important
     * to specify a TAG so that the pending/ongoing requests can be cancelled.
     *
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }

}

BaseController.java

public class BaseController extends Controller {

    /**
     * A singleton instance of the application class for easy access in other places
     */
    private static Controller sInstance;

    private static String mToken = null;

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize the singleton
        sInstance = this;
    }

    public static void setMtoken(String token){
        mToken = token;
    }

    public static String getMtoken(){
        return mToken;
    }

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized Controller getInstance() {
        return sInstance;
    }


}

CustomRequest.java

public class CustomRequest extends Request<JSONObject> {

    private Response.Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomRequest(String url, Map<String, String> params,
                         Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    public CustomRequest(int method, String url, Map<String, String> params,
                         Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = reponseListener;
        this.params = params;
    }

    @Override
    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
    };

    @Override
    protected void deliverResponse(JSONObject response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

}

最后这是一个真正的API调用:

public void login(final VolleyCallback<String> callback, String username, String password) {

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", username);
        params.put("password", password);

        CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST,
                API_URL_LOGIN, params,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray account = response.optJSONArray("account");

                            if (account!=null) {

                                account = response.getJSONArray("account");

                                JSONObject account2 = account.getJSONObject(0);
                                String token = account2.getString("token");

                                if (token!="null" && token!=null && token!="" && !token.isEmpty()) {

                                    callback.onSuccess(token);

                                } else {

                                    // token doens't set
                                    String result = "NO_TOKEN";
                                    callback.onSuccess(result);
                                }
                            } else {
                                // WRONG PASSWORD
                                String result = "WRONG_PASSWORD";
                                callback.onSuccess(result);
                            }


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

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError response) {
                if(response instanceof NoConnectionError) {
                    /*
                    showDialog(LoginActivity.this,
                            LoginActivity.this.getString(R.string.title_no_internet_connection),
                            LoginActivity.this.getString(R.string.message_no_internet_connection));*/
                }
            }

        });

        // add the request object to the queue to be executed
        BaseController.getInstance().addToRequestQueue(jsObjRequest);

    }

1 个答案:

答案 0 :(得分:7)

您可以在将请求添加到队列

之前将重试策略设置为该请求
Route::get('auth/check', 'AuthenticationController@check');

This堆栈溢出问题可以帮到你。