Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry a connection on timeout in Java

Tags:

java

I have a method (below) that pulls down and returns the source of a webpage as a String. It all works fine and dandy, but when the connection times out, the program throws an exception and exits. Is there a better method to do this that would allow it to try again on timeout, or is there a way to do it within this method?

public static String getPage(String theURL) {
    URL url = null;
    try {
        url = new URL(theURL);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        exitprint();
    }
    InputStream is = null;
    try {
        is = url.openStream();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        exitprint();
    }
    int ptr = 0;
    StringBuffer buffer = new StringBuffer();
    try {
        while ((ptr = is.read()) != -1) {
            buffer.append((char)ptr);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        exitprint();
    }

    return buffer.toString();
}
like image 533
InsanityOnABun Avatar asked Sep 05 '11 21:09

InsanityOnABun


2 Answers

I think AOP and Java annotations is a good option. I would recommend to use a read-made mechanism from jcabi-aspects:

@RetryOnFailure(attempts = 2, delay = 10)
public String load(URL url) {
  return url.openConnection().getContent();
}
like image 181
yegor256 Avatar answered Oct 21 '22 03:10

yegor256


Here's a refactoring of your code that should retry the download N times. Haven't tested it though, but it should kick you off in the right direction.

public static String getPage(String theURL) {

    URL url = null;
    try {
        url = new URL(theURL);
    } catch (MalformedURLException e) {
        e.printStackTrace();
        exitprint();
    }

    for (int i = 0; i < N; i++) {

        try {
            InputStream is = url.openStream();

            int ptr = 0;
            StringBuffer buffer = new StringBuffer();

            while ((ptr = is.read()) != -1)
                buffer.append((char)ptr);

        } catch (IOException e) {
            continue;
        }

        return buffer.toString();
    }

    throw new SomeException("Failed to download after " + N + " attepmts");
}
like image 13
aioobe Avatar answered Oct 21 '22 02:10

aioobe