android如何知道HttpResponse需要多少时间来给出响应

问题描述

|| 我有一个应用程序,我想在它每次与互联网连接并从互联网获取数据时查找多少时间? 如果需要更多时间,那么我想警告用户“ Internet连接问题” 所以我怎么知道要花多少时间,在我给我的应用程序的功能下面,我用的是ѭ0where.plz告诉我如何获得需要多少时间才能给出响应
 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());
            }
        }
    }
}
谢谢。     

解决方法

           ..如果需要更多时间,那么我想   警告... 由于您知道最佳时间,因此应该得到响应,为什么在创建连接时不指定超时。有关如何设置超时的信息,请参见下面的代码片段。然后,您捕获超时错误,并通知该服务时间太长而无法响应。
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params,5000);
HttpConnectionParams.setSoTimeout(params,5000);

ClientExecutor executor = new ApacheHttpClient4Executor(httpClient);
参考: http://blog.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/ Android上的HTTP连接超时无法正常工作     ,        以上答案也被实现了... 最简单的逻辑方法是…… 1)在一些变量中占用系统时间。 2)响应后,在另一个变量中获取系统时间。 3)减去差异,您将获得近似的响应时间。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...