Jsoup connections and retries

connection, java, jsoup

Solution

    ArrayList<String> l = new ArrayList();
    Document doc = null;
    int i = 0;
    boolean success = false;

    while( i < 3){
        try {
            doc = Jsoup.connect(sitemapPath).get();
            success = true;
            break;
        } catch (SocketTimeoutException ex){
            l.add("text...");               
        }
        catch (IOException e) {
        }           
        i++;
    }

    if(success){
        // Selector code ...
        Elements element = doc.select("loc");
    }

Problem

I'm using `JSoup` to connect to a website. I sometimes find that `JSoup`will have a connection timeout, when this happens I want `JSoup` to retry the connection and when it fails on the 3rd time it shall add a string to an array list. My code at the moment is: ``` try { Document doc = Jsoup.connect(sitemapPath) .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21") .timeout(10000) .get(); Elements element = doc.select("loc"); return element; } catch (IOException e) { return null; } ``` I was thinking of doing something with while loops but I have to return the element so I'm unsure how to do this.

Original source