我已经编写了一个代码来查找网页的响应时间,但它总是如此 给0时间。可以有人plz完成此代码以获得响应时间
mycode
import java.io.*;
import java.net.URL;
public class NewClass {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
URL myURL = new URL("https://stackoverflow.com/");
long finish = System.currentTimeMillis();
long totalTime = finish - start;
System.out.println("Total Time for page load - "+totalTime);
}
}
答案 0 :(得分:0)
你可以用
来做HttpURLConnection connection = null;
try {
URL url = new URL("http://stackoverflow.com/");
connection = (HttpURLConnection) url.openConnection();
long start = System.currentTimeMillis();
String jsonResponse = myInputStreamReader(connection.getInputStream());
long finish = System.currentTimeMillis();
long totalTime = finish - start;
System.out.println("Total Time for page load - " + totalTime);
} catch (Exception e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
static public String myInputStreamReader(InputStream in) throws IOException {
StringBuilder sb = null;
try {
InputStreamReader reader = new InputStreamReader(in);
sb = new StringBuilder();
int c = reader.read();
while (c != -1) {
sb.append((char) c);
c = reader.read();
}
reader.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return sb.toString();
}
答案 1 :(得分:0)
以下是您的问题的答案:
即使不使用java.net.URL
和java.net.HttpURLConnection
类中的selenium和apache,您也可以找到网页的响应时间,如下所示 -
import java.net.HttpURLConnection;
import java.net.URL;
public class Q44304154_response_time_of_webpage_2 {
public static void main(String[] args) throws Exception {
long start = 0;
long finish = 0;
String stack_url = "https://stackoverflow.com/";
try {
URL url = new URL(stack_url);
HttpURLConnection httpUrlConnect = (HttpURLConnection) url.openConnection();
httpUrlConnect.setConnectTimeout(5000);
start = System.currentTimeMillis();
httpUrlConnect.connect();
if (httpUrlConnect.getResponseCode() == 200)
{
finish = System.currentTimeMillis();
System.out.println(stack_url + " - " + httpUrlConnect.getResponseMessage() + " took " + (finish-start) + " Milli Seconds.");
}
if (httpUrlConnect.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND)
{
System.out.println(
stack_url + " - " + httpUrlConnect.getResponseMessage() + " - " + httpUrlConnect.HTTP_NOT_FOUND);
}
}
catch (Exception e)
{
}
System.out.println("Total Time for page load - "+ (finish-start));
}
}
如果这回答你的问题,请告诉我。