Download pdf from url in android

I need to display a pdf file in webview using this link https://col1.3yd.co:8087/api/getDoc?username=test&password=12345678&doc_id=dc_1

The problem is when I open this link in web view using google docs online view then I get the error "Oops! Could not display this image".

https://docs.google.com/gview?embedded=true&url=https://col1.3yd.co:8087/api/getDoc?username=test&password=12345678&doc_id=dc_1

Having tried too many methods from stackoverflower, I use this code to download a pdf file. The problem is loading every time file and its time. Is there any other way to display a file in webview.

 private void downloadAndOpenPDF(){

 progressDialog = new DLProgressDialog(context);
            progressDialog.show();

    new Thread(new Runnable() {
        public void run() {


            Uri path = Uri.fromFile(downloadFile(download_file_url));
            try {
                if(progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            } catch (ActivityNotFoundException e) {

            }
        }
    }).start();

}

private File downloadFile(String dwnload_file_path) {
    File file = null;
    try {
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        // connect
        urlConnection.connect();
        // set the path where we want to save the file
        File SDCardRoot = Environment.getExternalStorageDirectory();
        // create a new file, to save the downloaded file
        file = new File(SDCardRoot, dest_file_path);
        FileOutputStream fileOutput = new FileOutputStream(file);
        // Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();
        // this is the total size of the file which we are
        // downloading
        totalsize = urlConnection.getContentLength();
        // create a buffer...
        byte[] buffer = new byte[1024 * 1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            per = ((float) downloadedSize / totalsize) * 100;
              }
        // close the output stream when complete //
        fileOutput.close();

    } catch (final MalformedURLException e) {

    } catch (final IOException e) {

    } catch (final Exception e) {

    }
    return file;
}
+4

All Articles