且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用jsoup下载大的pdf

更新时间:2023-12-03 21:09:58

我认为,***通过HTTPConnection下载任何二进制文件:

I think, it's better to download any binary file via HTTPConnection:

    InputStream input = null;
    OutputStream output = null;
    HttpURLConnection connection = null;
    try {
        URL url = new URL("http://example.com/file.pdf");
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return "Server returned HTTP " + connection.getResponseCode()
                    + " " + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        // download the file
        input = connection.getInputStream();
        output = new FileOutputStream("/sdcard/file_name.extension");

        byte data[] = new byte[4096];
        int count;
        while ((count = input.read(data)) != -1) {
            output.write(data, 0, count);
        }
    } catch (Exception e) {
        return e.toString();
    } finally {
        try {
            if (output != null)
                output.close();
            if (input != null)
                input.close();
        } catch (IOException ignored) {
        }

        if (connection != null)
            connection.disconnect();
    }

Jsoup用于解析和加载HTML页面,而不是二进制文件.

Jsoup is for parsing and loading HTML pages, not binary files.