【问题标题】:Android volley JsonObjectRequest takes too longAndroid volley JsonObjectRequest 耗时太长
【发布时间】:2016-08-19 15:50:57
【问题描述】:

我现在正在寻找几天来弄清楚为什么我的 POST 请求需要这么长时间才能加载。我正在使用 volley 库而不是 HTTPRequest。

这就是我执行请求的方式:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

...

JSONObject jsonObject = new JSONObject();
jsonObject.put("geoLong", longitude);
jsonObject.put("geoLat", latitude);
jsonObject.put("radius", 5);
JsonObjectRequest jsonRequest = new   JsonObjectRequest(Request.Method.POST, URL,
    jsonObject, createResponseListener(), createErrorListener());
jsonRequest.setShouldCache(false);
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(15000, 2, 1));
jsonRequest.setTag(requestTag);
requestQueue.add(jsonRequest);

该请求大约需要 10-15 秒才能加载,直到我收到响应,这太荒谬了,因为响应大小约为 1886 字节。我用良好的 WLAN 连接和 3G 测试了它。

如果我在笔记本电脑上通过 WLAN 向 Postman 发出请求,它只需要大约 400 毫秒,所以这不是服务器端问题。我很困惑,为什么需要这么长时间才能提出这个凌空请求,我做错了什么吗?

【问题讨论】:

  • 你是如何测量时间的?我在这里看不到任何东西。
  • 我不会在手机上测量时间,这只是我的评估。
  • 那你怎么知道需要这么长时间?你怎么知道问题不在你的显示代码中?还是在其他十几个地方?还是说有问题?
  • 这是在调试器中还是没有?我注意到一些 Gson 序列化在调试器上运行时需要很长时间,而没有它的速度非常快。也许您应该尝试返回一个字符串,以便查看是请求还是 json 转换器花时间。 @GabeSechan 有正确的想法,您需要更好地检测您的代码以识别问题。

标签: android performance http-post android-volley


【解决方案1】:

通常截击不会花费更多时间。 您可以自行检查。

private long mRequestStartTime;

public void performRequest()
{
    mRequestStartTime = System.currentTimeMillis(); // set the request start time just before you send the request.

    JsonObjectRequest request = new JsonObjectRequest(URL, PARAMS, 
        new Response.Listener<JSONObject>() 
        {
            @Override
            public void onResponse(JSONObject response) 
            {
                // calculate the duration in milliseconds
                long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
            }
        },
        new Response.ErrorListener() 
        {
            @Override
            public void onErrorResponse(VolleyError error) 
            {
                long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
            }
        });

    requestQueue.add(request);
} 

如果您仍然会遇到问题,那么您可以使用 Retrofit:http://square.github.io/retrofit/

【讨论】:

  • 我按你说的测量了时间,问题是json解析。感谢您的帮助!
猜你喜欢
  • 2013-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多