Android检查发布请求的速度

时间:2015-01-05 21:22:31

标签: android android-asynctask

我正在尝试检查Post请求执行的速度。我在AsyncTask中执行请求。

这就是我目前正在检查执行时间的方式

            long start = System.nanoTime();
            new POSTTask().execute();
            long end = System.nanoTime() - start;

我不确定这给出的时间是否是Post请求所需的实际时间。在AsyncTask中,我唯一要做的就是以下

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost request = new HttpPost(url);

            List<NameValuePair> postParameters = new ArrayList<>();
            postParameters.add(new BasicNameValuePair("test", "tets1"));

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);

            request.setEntity(formEntity);
            HttpResponse response = httpClient.execute(request);
            result = EntityUtils.toString(response.getEntity());

            Log.i("Result", result);
        } catch (IOException e) {
            e.printStackTrace();
        }

我是以正确的方式还是以错误的方式解决这个问题?

3 个答案:

答案 0 :(得分:0)

不,这不是实际时间。您正试图在主线程上获得执行时间,但您的帖子查询在后台的另一个线程中运行。

像这样使用

try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);

        List<NameValuePair> postParameters = new ArrayList<>();
        postParameters.add(new BasicNameValuePair("test", "tets1"));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);

        request.setEntity(formEntity);
        long start = System.nanoTime();
        HttpResponse response = httpClient.execute(request);
        long end = System.nanoTime() - start;
        // Print value of end here
        result = EntityUtils.toString(response.getEntity());

        Log.i("Result", result);
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

不,这是错的。 execute上的AsyncTask方法会在请求执行之前立即返回。

如果您将时间码移动到AsyncTask,特别是将它放在这一行

        HttpResponse response = httpClient.execute(request);

你会得到实际的时间。

答案 2 :(得分:0)

这是错误的,因为这些行没有按顺序执行。

new POSTTask().execute();

开始一个新的线程意味着你的2个时间戳将真正地靠近在一起,就像毫秒相隔并且不准确

你应该在doInBackground

中完成所有时间
相关问题