1
votes

I am trying to parse some url's with Jsoup but I get this error:

java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)

here is my code:

public Elements getLinks(String link){
    Document doc = null;
    Elements links = null;
    try {
        doc = Jsoup.connect(link)
                 .userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0")
                 .referrer("http://www.google.com") 
                 .timeout(5000) //it's in milliseconds, so this means 5 seconds.              
                 .get();

        links = doc.select("a[href]");
    }  
    catch (ConnectException e){
        e.printStackTrace();
    }
    catch (UnsupportedMimeTypeException e){
        e.printStackTrace();
    }
    catch (SocketTimeoutException e){
        e.printStackTrace();
    }
    catch (SSLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        if(e.getCause() instanceof SocketTimeoutException) {
            try {
                throw new SocketTimeoutException();
            } catch (SocketTimeoutException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
   }
        e.printStackTrace();
    }

    return links;
}

I have a catch section for the ConnectException but my program stops.. Any ideas how to fix this problem?

1
Well what do you expect? The server refused the connection and there's very little you can do about it. Are you supposed to be able to connect to it? Do you have the correct protocol (http/https)?Kayaman
I don't want to connect, I just want my program not to stop. I don't care for a broken URL.yasuo
Well that method won't stop your program. It'll just print the stacktrace and return null. If the rest of your program can't handle that, then the problem is there.Kayaman
Thank you, that's the problemyasuo
Please make your code more readable by using multicatch.lonesome

1 Answers

1
votes

Answer proposed by Kayaman:

Well that method won't stop your program. It'll just print the stacktrace and return null. If the rest of your program can't handle that, then the problem is there.