Search code examples
javadownloadjsoup

Is it a good way to download a file from internet using jsoup library?


I am using Jsoup Library for downloading a file from internet. I don't know it's a good way to use Jsoup library to download a file from internet using Jsoup or not (because Jsoup is a HTML parser). I am using the following code to downlaod a file:

final Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Connection.Response response = Jsoup.connect("URL")
                .ignoreContentType(true)
                .execute();

            BufferedInputStream inputStream = response.bodyStream();
            FileOutputStream fos = new FileOutputStream("location");
            byte[] buffer = new byte[1024];
            int len;
            while((len = inputStream.read(buffer)) != -1){
                fos.write(buffer, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
t.start();

Will there be a problem if i use Jsoup library for downloading a file? Thanks.


Solution

  • As you have mentioned yourself , jsoup is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods.

    It might be working for you now, but you might need to add some headers, timeouts etc in near future. Hence it is better to use a HTTPClient to do this job. HTTPClients are meant to make client side HTTP calls, which would do the job better than JSoup.

    One such HTTPClient from apache: http://hc.apache.org/httpclient-3.x/