rahul
rahul

Reputation: 215

url response time

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

Answers (4)

moto_beats
moto_beats

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

Costi Ciudatu
Costi Ciudatu

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 the connected field having the value true), 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

skaffman
skaffman

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:

  1. Move url.openConnection() inside the loop
  2. Add a call to conn.getInputStream() after the conn.connect().
  3. (Maybe) read the contents of the InputStream - this may not be necessary, depending on what you're trying to measure
  4. Most of all, read the JavaDoc for HttpURLConnection to properly understand what the methods really do.

Upvotes: 2

Subir Kumar Sao
Subir Kumar Sao

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

Related Questions