We help IT Professionals succeed at work.
Get Started

How do I set a Readtimeout in Java URLConnection?

Last Modified: 2013-12-02
I am using Java to connect to a url and read the contents of the page.
The code looks like what I have posted in the attachment. However, the connect and/or read timeouts don't seem to work and the program hangs. Examples of urls which can't be read are: http://www.ajc.com and http://www.statesman.com. I can supply more examples of such urls, although they can be read perfectly all right in a browser.

I have also tried:
System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
System.setProperty("sun.net.client.defaultReadTimeout", "5000");
but this too doesn't seem to work.

try {
		newURL = new URL (CURLVal);
		HttpURLConnection conn = (HttpURLConnection) newURL.openConnection();
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 4.0)");
		InputStreamReader isr = new InputStreamReader(conn.getInputStream());
		BufferedReader in = new BufferedReader(isr);
		String inputLine;
         while ((inputLine = in.readLine()) != null)
	    		contents = contents + inputLine;
			catch (SocketTimeoutException e) {
			catch (Exception e) {

Open in new window

Watch Question
Distinguished Expert 2020
This problem has been solved!
Unlock 1 Answer and 11 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE