Android排名DefaultRetryPolicy无法按预期工作

时间:2016-02-19 13:15:11

标签: android android-volley

所以,我有这个Volley PUT请求:

private boolean syncCall(JSONObject jsonObject, final VolleyCallback
        callback) {

    final ProgressDialog progDailog = new ProgressDialog(context);

    final Boolean[] success = {false};

    progDailog.setMessage("...");
    progDailog.setIndeterminate(false);
    progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

    progDailog.setCancelable(false);
    progDailog.show();

    final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);

    RequestQueue queue = Volley.newRequestQueue(context, new HurlStack());

    final String token = prefs.getString("token", null);

    String URL = Constants.getUrlSync();
    String param1 = String.valueOf(prefs.getInt("pmp", 1));
    String param2 = String.valueOf(prefs.getInt("ei", 1));

    URL = URL.replace("[x]", param1);
    URL = URL.replace("[y]", param2);

    //pegar id pmp e IE corretas
    JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request
            .Method.PUT, URL, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    callback.onSuccess(response + "");
                    success[0] = true;
                    progDailog.dismiss();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    callback.onFailure(error);
                    tokenFailure(error);
                    success[0] = false;
                    progDailog.dismiss();
                }
            }) {


        @Override
        public Map<String, String> getHeaders() throws
                AuthFailureError {

            HashMap<String, String> headers = new HashMap<>();
            headers.put("Token", token);

            return headers;
        }
    };

    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

    jsObjRequest.setRetryPolicy(policy);


    queue.add(jsObjRequest);

    return success[0];
}

我的问题是我发送了一个非常大的JSON,所以5秒的默认超时是不够的。所以,我试图将超时时间增加到30秒并且弄乱DefaultRetryPolicy以增加重试次数。

问题是,它使timeouting保持5秒,甚至不会重试一次!

重试时是否需要监听器或回调?我对DefaultRetryPolicy做错了什么?请帮忙,这个问题让我疯狂......

2 个答案:

答案 0 :(得分:5)

您需要使用DefaultRetryPolicy吗?

因为您可以定义自己的。

而不是:

RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,     
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,     
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

试试这个:

jsObjRequest.setRetryPolicy(new RetryPolicy() {
    @Override
        public int getCurrentTimeout() { 
            // Here goes the new timeout
            return mySeconds; 
        }
        @Override
        public int getCurrentRetryCount() { 
            // The max number of attempts
            return myAttempts; 
        }
        @Override
        public void retry(VolleyError error) throws VolleyError {
            // Here you could check if the retry count has gotten
            // To the max number, and if so, send a VolleyError msg
            // or something    
        }
    });

答案 1 :(得分:1)

我不确定为什么重试时间对您的代码没有影响,但我确实发现了类似的问题here

相反,我可以告诉你一些我认为在你的代码中没有的东西,并建议你采用我的Volley模型。

首先,您要为您正在制作的每个请求创建一个新的请求队列。这不是很酷,你应该有一个RequestManager单例,它包含一个请求队列并使用它。

其次,我不知道这是否会影响重试时间,我有一个基本请求类并在构造函数中设置重试时间。然后,每当我必须实现一种新类型的请求时,我都会扩展这个类。然后,我创建一个请求实例,设置回调,并将其传递给请求管理器。请求管理器将它添加到我正在讨论的一个请求队列中。

此外,如果您还没有,我建议您使用Gson库来解析JSON对象。

这是我使用的基本请求类:

/**
* Created by Daniel on 2/6/2016.
*/
public class GsonRequest<T> extends Request<T> {

protected Context context;
protected final Gson gson = new Gson();
protected final Class<T> clazz;
protected final TypeToken typeToken;
protected Map<String, String> headers;
protected Map<String, String> params;
protected final Response.Listener<T> listener;

/**
 * Make a GET request and return a parsed object from JSON.
 *
 * @param url   URL of the request to make
 * @param clazz Relevant class object, for Gson's reflection
 */
public GsonRequest(final Context context, final int requestMethod, String url, Class<T> clazz, Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(requestMethod, url, errorListener);
    this.context = context;
    this.clazz = clazz;
    this.listener = listener;
    this.headers = new HashMap<>();
    typeToken = null;
    setRetryPolicy();
}

/**
 * Make a GET request and return a parsed object from JSON.
 *
 * @param url       URL of the request to make
 * @param typeToken Relevant typeToken object, for Gson's reflection
 */
public GsonRequest(final Context context, final int requestMethod, String url, TypeToken typeToken, Response.Listener<T> listener, Response.ErrorListener errorListener) {
    super(requestMethod, url, errorListener);
    this.context = context;
    this.typeToken = typeToken;
    this.listener = listener;
    this.headers = new HashMap<>();
    clazz = null;
    setRetryPolicy();
}

@Override
protected Map<String, String> getParams() throws AuthFailureError {
    return params != null ? params : super.getParams();
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    //TODO add headers here
    return headers;
}

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

@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
    try {
        String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        JSONObject jsonObject = new JSONObject(json);
        if (clazz != null) {
            return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response));
        } else {
            return Response.success((T) gson.fromJson(json, typeToken.getType()), HttpHeaderParser.parseCacheHeaders(response));
        }
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JsonSyntaxException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException e) {
        return Response.error(new ParseError(e));
    }
}

protected void setRetryPolicy() {
    //TODO set your retry policy here
    setRetryPolicy(new DefaultRetryPolicy(
            30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
}`enter code here`

这对我来说就像一个魅力。希望它有所帮助,如果您需要任何进一步的帮助,请与我联系