Java – Close the Jsoup connection

Close the Jsoup connection… here is a solution to the problem.

Close the Jsoup connection

I need some help understanding the basics of Jsoup. The following code works, but I’m wondering if the connection needs to be closed somehow. I couldn’t find any information about it on the Jsoup website. If the application persists after the background method executes, I get a message in the log cat every five minutes or so saying “Request time failed: java.net.SocketException: Address family not supported by protocol”. So I want to make sure I’m not consuming data unnecessarily. Thank you.

            protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
        //  connect to web page based on user input
            Document doc = Jsoup.connect(routeURL).get();


        //  select relevant page elements
            Elements fareStageNumbers = doc.getElementsByClass("fare_stages_inner_table");

       //   test printing out fare stage numbers
            for(Element div : fareStageNumbers){

                Log.v(TAG, div.text());

            }



        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

Log messages:

    01-12 20:58:28.755: D/SntpClient(78): request time failed: java.net.SocketException: Address family not supported by protocol
    01-12 21:03:28.765: D/SntpClient(78): request time failed: java.net.SocketException: Address family not supported by protocol
    01-12 21:08:28.775: D/SntpClient(78): request time failed: java.net.SocketException: Address family not supported by protocol

Solution

Jsoup closes the connection itself after the request is completed:

// from 'org.jsoup.helper.HttpConnection' class
static HttpConnection.Response execute(Connection.Request req, HttpConnection.Response previousResponse) throws IOException {
    // ...
    HttpURLConnection conn = createConnection(req);
    HttpConnection.Response res;
    try {
        // ...
    } finally {
        // per Java's documentation, this is not necessary, and precludes keepalives. However in practise,
        // connection errors will not be released quickly enough and can cause a too many open files error.
        conn.disconnect();
    }
    // ...
}

Exception: Does your URL contain a protocol (URLs start with, for example http:// )?

Related Problems and Solutions