我正在尝试构建网站监控系统。我需要计算网站响应时间或总加载时间。
答案 0 :(得分:2)
如果要计算http请求和响应之间的往返,可以使用apache http components。这曾经被称为apache http客户端。
这是我用于发出请求的一些示例代码。您可以在请求之前和之后获取时间戳。
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);
}
}
}