Reputation: 215
i am making a program to get the response time by any url...
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
for(int i=0; i<20; i++ ) {
long starTime = System.currentTimeMillis();
conn.connect();
long elasedTime = System.currentTimeMillis() - starTime;
System.out.println(elasedTime);
conn.disconnect();
}
but mostoff the time its giving me output result as 0.. plz someone help me out!! i need to capture the time from last bit of my request to the first bit of response.
Upvotes: 0
Views: 6186
Reputation: 39
conn.connect() establishes a connection (TCP three-way handshake) but it does not "GET" the content at the URL. You can use Wireshark to verify this.
So know that with this method you are not measuring the response time to receive the content at the URL.
Upvotes: 0
Reputation: 38195
There's not much of a response that you could expect from merely opening a connection.
Moreover, your call to connect()
is most likely ignored as your connection is already open -- that's why you get a 0 time. From the URLConnection#connect()
javadoc:
If the
connect
method is called when the connection has already been opened (indicated by theconnected
field having the valuetrue
), the call is ignored.
If you want to actually retrieve a response, fetch the InputStream
(call conn.getInputStream()
) and then read everything in it.
Upvotes: 1
Reputation: 403441
Simply opening the connection isn't going to take any time at all. You need to actually fetch the content from the URL to get a meaningful benchmark. You've also moved url.openConnection()
to outside of the benchmark loop, which is a bit bizarre.
So change your loop so that:
url.openConnection()
inside the loopconn.getInputStream()
after the conn.connect()
. InputStream
- this may not be necessary, depending on what you're trying to measureHttpURLConnection
to properly understand what the methods really do.Upvotes: 2
Reputation: 8401
Java api says the connection is made when you call the conn.connect() but the connection is not made unless you get the InputStream from the connection.
connection.getInputStream()
Upvotes: 0