【问题标题】:how can i stay longer for response from URL in android?我怎样才能在 android 中停留更长时间来响应来自 URL 的响应?
【发布时间】:2017-10-11 22:48:00
【问题描述】:

我使用这种方法在服务器中发送一个 json 对象并请求接收数据:

private void makeJsonObjectRequest1() {
    message = "abcd";
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            G.myurl, js, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject jsonObject) {

            Log.d("***1", jsonObject.toString());
            try {
                Log.d("***1", jsonObject.toString());
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("***2", "Exc");
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d("***3", "Error: " + error.getMessage());

            if (error instanceof NetworkError) {
                message = "internet";
            } else if (error instanceof ServerError) {
                message = "server";
            } else if (error instanceof AuthFailureError) {
                message = "Cannot connect to Internet...Please check your connection!";
            } else if (error instanceof ParseError) {
                message = "Parsing error! Please try again after some time!!";
            } else if (error instanceof NoConnectionError) {
                message = "Cannot connect to Internet...Please check your connection!";
            } else if (error instanceof TimeoutError) {
                message = "Connection TimeOut! Please check your internet connection.";
            }
            Log.i("***4", "Error:" + message);
        }
    });
    G.getInstance().addToRequestQueue(jsonObjReq);
}

我收到“解析错误!请稍后再试!!” 在服务器中我收到来自应用程序的两个请求! 我怎么解决这个问题? 如果你能帮助我,谢谢

【问题讨论】:

    标签: java php android android-volley


    【解决方案1】:

    要增加超时时间,您需要在 Volley 中设置重试策略,因此在将您的请求添加到请求队列之前将其设置为:

        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
        30000, // This is your time in milliseconds for this its 30 seconds
        DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    

    记住时间以毫秒为单位,您还可以设置回退限制和重试次数。

    为避免两次执行相同的请求,请将重试次数更改为您想要的次数,在您的情况下,我们希望 Volley Request NOT 重试,因为如果重试,您的服务器可能已经收到两个请求,因此整个解决方案变为:

    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
    30000, //the number of milliseconds to try out I have put 30seconds==30000milliseconds
    0,  // maxNumRetries = 0 means no retry then volley wont retry
    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    

    您可以查看一些官方培训from this link 并自己探索课程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多