【问题标题】:android how to know HttpResponse takes how much time for giving responseandroid如何知道HttpResponse需要多少时间来给出响应
【发布时间】:2025-11-27 17:00:01
【问题描述】:

我有一个应用程序,每次连接互联网并从互联网获取数据时,我想查找它需要多长时间? 如果需要更多时间,那么我想向用户发出“互联网连接问题”的警告

那么我怎么知道它需要多长时间。在我提供的应用程序的功能下方,HttpResponse 我使用了。请告诉我如何获得给出响应需要多少时间

 String page = executeHttpGet("http://192.168.1.109/temp/android.php");

 private String executeHttpGet(String URL) throws Exception {

    BufferedReader bufferedReader = null;
    try {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
                "android");
        HttpGet request = new HttpGet();
        request.setHeader("Content-Type", "text/plain; charset=utf-8");
        request.setURI(new URI(URL));
        HttpResponse response = client.execute(request);
        bufferedReader = new BufferedReader(new InputStreamReader(response
                .getEntity().getContent()));

        StringBuffer stringBuffer = new StringBuffer("");
        String line = "";

        String NL = System.getProperty("line.separator");
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line + NL);
            System.out.print(stringBuffer);
        }
        bufferedReader.close();
        page = stringBuffer.toString();
        System.out.println(page + "page");
        return page;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                Log.d("BBB", e.toString());
            }
        }
    }
}

谢谢。

【问题讨论】:

  • 你应该在http请求中设置响应时间。

标签: android


【解决方案1】:

..如果需要更多时间,那么我想 警告...

既然您知道应该得到响应的最佳时间,为什么不在创建连接时指定超时。请参阅下面的代码 sn-p 了解如何设置超时。然后,您捕获超时错误并通知服务太长而无法响应。

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);

ClientExecutor executor = new ApacheHttpClient4Executor(httpClient);

参考:

  1. http://blog.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/
  2. Http connection timeout on Android not working

【讨论】:

    【解决方案2】:

    上面的答案也实现了...

    最简单的逻辑方式是……

    1) 在某个变量中占用系统时间。

    2) 响应后在另一个变量中获取系统时间。

    3) 取差值,您将获得近似的响应时间。

    【讨论】:

      最近更新 更多