Android: how to download a file from webview dynamic url

In my application, I use web browsing to go to the site, automatically filling out the web form using javascript, and then submit to get a link to the CSV export file. The link looks like this: XYZ.com/TEST/index/getexport?id=130.

I want to download the file that this URL points to, then read it in the local database, but I had problems downloading the linked file.

If I just try to open the URL in webview, I get an error message from a webpage stating that there is no such file.

If I use Download Manager to download it myself, the source code is downloaded as an html file, not the associated .csv file.

I can open the url with the intent ACTION_VIEW, and the browser (chrome) downloads the correct file, but this way I do not have a notification that the download is complete.

Any ideas on how to download my .CSV file?

0
android webview
source share
2 answers

To download a file from webview, use this:

mWebView.setDownloadListener(new DownloadListener(){ public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength){ Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); 

Hope this helps.

0
source share

You can resort to manually downloading the file from the URL using AsyncTask.

Here id is the background part:

 @Override protected String doInBackground(Void... params) { String filename = "inputAFileName"; HttpURLConnection c; try { URL url = new URL("http://someurl/" + filename); c = (HttpURLConnection) url.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); } catch (IOException e1) { return e1.getMessage(); } File myFilesDir = new File(Environment .getExternalStorageDirectory().getAbsolutePath() + "/Download"); File file = new File(myFilesDir, filename); if (file.exists()) { file.delete(); } if ((myFilesDir.mkdirs() || myFilesDir.isDirectory())) { try { InputStream is = c.getInputStream(); FileOutputStream fos = new FileOutputStream(myFilesDir + "/" + filename); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = is.read(buffer)) != -1) { fos.write(buffer, 0, len1); } fos.close(); is.close(); } catch (Exception e) { return e.getMessage(); } if (file.exists()) { return "File downloaded!"; } else { Log.e(TAG, "file not found"); } } else { Log.e(TAG, "unable to create folder"); } } 

It might be advisable to reorganize it so that the file is returned. You will then receive the file as an argument in onPostExecute as soon as the download is complete.

0
source share

All Articles