Learner
Learner

Reputation: 21393

Java Jsoup program in Eclipse throws java.net.SocketTimeoutException: connect timed out

I am working on a simple Jsoup program using my Eclipse, but when I try to run the program and add more steps to my program then I am getting error as java.net.SocketTimeoutException: connect timed out.

This code works fine:

public static void main(String[] args) {
    Document doc;
    try {
        doc = Jsoup.connect("http://google.com").get();
        System.out.println("doc is = " + doc);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and I get some XML data as output.

Now when I change this program to:

public static void main(String[] args) {
    Document doc;
    try {
        // need http protocol
        doc = Jsoup.connect("http://google.com").get();
        System.out.println("doc is = " + doc);

        // get page title
        String title = doc.title();
        System.out.println("title : " + title);

        // get all links
        Elements links = doc.select("a[href]");
        for (Element link : links) {
            // get the value from href attribute
            System.out.println("\nlink : " + link.attr("href"));
            System.out.println("text : " + link.text());
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then I am getting exception as: java.net.SocketTimeoutException: connect timed out

It seems I need to set timeout option, please let me know where I can do that in eclipse?

I have referred below SO posts but still facing same issue, also I don't have any proxy in between to access the internet:

Sometimes java.net.SocketTimeoutException: Read timed out. Sometimes not

Exception in thread “main” java.net.SocketTimeoutException: connect timed out at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)

Upvotes: 1

Views: 5240

Answers (2)

Ignacio Rubio
Ignacio Rubio

Reputation: 1354

A timeout of zero is treated as an infinite timeout.

Jsoup.connect("http://google.com").timeout(0).get();

Upvotes: 1

Reimeus
Reimeus

Reputation: 159754

You can specify the timeout though the Connection

Connection connection = Jsoup.connect("http://google.com");
connection.timeout(5000); // timeout in millis
doc = connection.get();

Upvotes: 2

Related Questions