This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Probably the fault is not the client (your code), but the server ( web service). This error means that the URL waited the specified time but didn't get any reponse so it automatically closed the connection.
But Sometimes it connect and sometime not. Like first time if I hit its give me data when i hit second time its gives me connection timeout.Sometimes it works for 8-9 times & then connection timeout further.That is really strange for me. If this is the target server issue, then how can i debug this.
Basically, if the problem is the server side which can't accept new connection, so if you try "telnet www.google.com 80" you will get the same problem. In other words, the server side handles to accept the connection (using a pool of threads with a listener or NIO, but the details doesn't matter) but it is too busy (all the working threads are busy to handle other connections). We can create an analogy like when you call someone phone that is already in a call. That person can be aware of the call, but he is already answering someone, so he need to finish the old call to handle the new one. If you doesn't want to wait enough (timeout parameter) you will end the call.
You can use others tools to simulate this issue creating stress tests. You can use JMeter (or SoapUI or other tool) to simulate 20 (or more) connections at the same time and see if the server side is able to answer them.
Yes, If i am trying telnet www.google.com 80 its giving me an error Connect Failed. So what you suggest, As server from where we getting the url is of other party and we cant check on our end, we have only url.
You seem to find it surprising that it sometimes takes more than 20 seconds to connect to that URL. Is that surprise based on actual experience with the web service? Those of us trying to answer your question don't have any experience with it, so it's quite possible that it has that sort of slow response time. In other words, don't ask us whether a response time of over 20 seconds is unexpected because we have no way of knowing.