3

I'm writing some code in Java to dowload stuff from urls and in my configuration some downloads should be handled by a proxy and others without it.

So I wrote this code (it works) to download all URL types but and I'd like to reduce the delay time before a ConnectException is thrown so the code can execute faster.

URL global_url = new URL("http://google.com");
Scanner sc = null;
try { 
    sc = new Scanner(global_url.openStream());
}
catch (ConnectException e) {
    try {
        System.setProperty("http.proxyHost", "my.host");
        System.setProperty("http.proxyPort", "my.port");
        sc = new Scanner(global_url.openStream());
        System.setProperty("http.proxyHost", "");
        System.setProperty("http.proxyPort", "");
    }
    catch (ConnectException exc) {
        //Do stuff
    }
}

Right now it takes approx. 10s before the exception is thrown and I'd like to reduce this time to 2s or 3s max.

Could I get some help? Thanks !

Jerome
  • 1,225
  • 2
  • 12
  • 23
  • What is the type of `global_url`? I'm assuning `URL`. – nanofarad Jul 09 '13 at 14:30
  • Of course global_url is of type URL yes ;) – Jerome Jul 09 '13 at 14:31
  • This code doesn't work anyway. Those system properties are only read once, and in any case you aren't clearing them. You need to have a good look at using java.net.Proxy. – user207421 Jul 09 '13 at 23:51
  • @EJP : I don't know why you are claiming this code doesn't work, it works perfectly on my program... when I have a local url where I don't need to use the proxy, I get the file instantly while when I want to have an "external" url, I catch the exception and get the file using the proxy... – Jerome Jul 18 '13 at 13:48

1 Answers1

5

You can set the timeout like this:

long connectTimeout = 3000;
URL global_url = new URL(urlPath);
URLConnection con = global_url.openConnection();
con.setConnectTimeout(connectTimeout);

where connectTimeout you can set as in milliseconds. As you need 3s timeout so set it as 3000.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • Thanks for your answer. Then I feed my Scanner with : Scanner sc = new Scanner(con.getInputStream()) ? – Jerome Jul 09 '13 at 14:37
  • Maybe you should add that when the timeout is finished, it raises a SocketTimeoutException and not a ConnectExcepion ;) Except from this point it works fine, thx again!! – Jerome Jul 09 '13 at 14:58