Nikolay Kuznetsov
Nikolay Kuznetsov

Reputation: 9579

URLConnection.getInputStream() : Connection timed out

I use the code from Sun's java tutorial

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("http://www.yahoo.com/");
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

Stack trace is same as Connection timed out. Why?

I suspect that might be problem with firewall but

  1. ping to google.com is okay
  2. it works in browser
  3. this approach fails for every URL I provide
  4. I use DJ WebBrowser component in other program and it works okay as a browser

How can I investigate more about this problem? Can I get to know which port numbers are going to be used when I run the code?

Thanks

Upvotes: 2

Views: 8271

Answers (2)

DCS
DCS

Reputation: 1

There is also a HttpURLConnection that might work better in some cases. It doesn't appear to disconnect in the same way.

URL url = new URL(address); 
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(callTimeout);

and so on.

Upvotes: 0

Deepak Bala
Deepak Bala

Reputation: 11185

Find the proxy that is used by your company and set it in your program. Quoting code from [1]

//Set the http proxy to webcache.mydomain.com:8080

System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setPropery("http.proxyPort", "8080");

// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();

// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null);

// From now on http connections will be done directly.

[1] - http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html

Upvotes: 4

Related Questions