如何用java计算网站的响应时间

how to calculate response time of a website in java

本文关键字:响应时间 网站 计算 何用 java      更新时间:2023-12-16

我正在尝试构建一个网站监控系统。我需要计算网站响应所需的时间或总加载时间。

如果您想计算http请求和响应之间的往返行程,可以使用apachehttp组件。这曾经被称为apachehttp客户端。

以下是我用于请求的一些示例代码。您可以在请求前后获取时间戳。

    HttpClient httpclient = new DefaultHttpClient();
    URIBuilder builder = new URIBuilder();
    URI uri = null;
    HttpEntity entity = null;
    InputStream inputStream = null;
    JSONObject jsonObject = null;
    URL url = this.getClass().getClassLoader().getResource("json" + File.separator + "newInstall.json");
    try {
        String json = FileUtil.readFile(url.getPath());
        builder.setScheme("http").setHost(host).setPort(8080).setPath(basePath + authResource)
                .setParameter("sig", "sig").setParameter("params", json);
        uri = builder.build();
        log.info("uri: {}", uri);
        HttpGet httpget = new HttpGet(uri);
        HttpResponse response = httpclient.execute(httpget);
        entity = response.getEntity();
        if (entity != null) {
            inputStream = entity.getContent();
            String jsonString = IOUtils.toString(inputStream, "UTF-8");
            jsonObject = new JSONObject(jsonString);
            log.info("auth response: {}", jsonString);
        }
    } catch (Exception e) {
        log.error("error", e);
    }finally {
        if(inputStream != null) {
            try {
                inputStream.close();
            }catch(Exception ex) {
                log.error("error closing input stream", ex);
            }
        }
    }