com.pdftron.pdf.utils.BasicHTTPDownloadTask.java Source code

Java tutorial

Introduction

Here is the source code for com.pdftron.pdf.utils.BasicHTTPDownloadTask.java

Source

//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2016 by PDFTron Systems Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

package com.pdftron.pdf.utils;

import android.content.Context;

import org.apache.commons.io.IOUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class BasicHTTPDownloadTask extends CustomAsyncTask<String, Void, Boolean> {

    private String mURL;
    private File mSaveFile;
    private BasicHTTPDownloadTaskListener mListener;

    public BasicHTTPDownloadTask(Context context, BasicHTTPDownloadTaskListener listener, String url,
            File saveFile) {
        super(context);
        mURL = url;
        mSaveFile = saveFile;
        mListener = listener;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        URL url;
        OutputStream filestream = null;
        try {
            url = new URL(mURL);

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            filestream = new BufferedOutputStream(new FileOutputStream(mSaveFile));

            IOUtils.copy(urlConnection.getInputStream(), filestream);

            filestream.close();
        } catch (MalformedURLException e) {
            return false;
        } catch (IOException e) {
            try {
                if (filestream != null)
                    filestream.close();
            } catch (IOException e2) {
            }
            return false;
        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean pass) {
        mListener.onDownloadTask(pass, mSaveFile);
    }

    public interface BasicHTTPDownloadTaskListener {
        void onDownloadTask(Boolean pass, File saveFile);
    }
}