Download URL File if exist. - android

Hi everyone I'm trying download file from url if exist… my problem is file downloaded without exist from server…
i will appreciate if anyone help me…
I can not figure out check if file exist download it if not ignore…
private void startDownload() {
// TODO Auto-generated method stub
String url = "http://example.com/file/krs.db";
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
// create empty directory if not exist
File appDir = new File(sdcardBaseDir + externalPath);
if (!appDir.exists())
appDir.mkdirs();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(sdcardBaseDir
+ externalPath + IcsvFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
}
}
Appreciate your help..

Use the code below to check whether your file is exist in the given url.
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
The method returns 'true' if file exists, Then download it.
Ignore otherwise.

If you connect to a HTTP URL, you will actually get back a HttpURLConnection object. It has a getResponseCode method that gives you the HTTP status code.

Related

Get content length method (getContentLength()) of the URLConnection class returns negative 1 (-1)

Below is my AsyncTask to download a PDF file from CloudBoost database. The code works and downloads the file; however, what does not work is the progress bar update because the file length returned is -1. Can someone give me a tip on how I can deal with this.
By the way loading.setProgress(progress[0]); line in the the progress update method is being initialized at the top of the class that this AsyncTask class is nested in.
class DownloadPdfFromInternet extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
int count;
try {
URL url = new URL(strings[0]);
URLConnection connection = url.openConnection();
connection.connect();
// get length of file
int lengthOfFile = connection.getContentLength();
Log.d("dozer74", "LengthOf File: " + lengthOfFile);
InputStream input = new BufferedInputStream(url.openStream(), 10 * 1024);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/" + pubName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / lengthOfFile));
// write data to file
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
loading.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String url) {
loading.dismiss();
openPdfFile();
}
}

how to get soundcloud audio download url by using audio file id

am using sound cloud search api. when i hit the search url it give me search results. every audio has stream url but not download url because it depends on setting of the uploader. Every none downloadable file also has download count more than 1. for example, when you'll hit this url
http://api.soundcloud.com/tracks.json?client_id=4346c8125f4f5c40ad666bacd8e96498&q=tere%20bin&limit=1
It'll give the search result like that
[{"kind":"track","id":63225776,"created_at":"2012/10/13 01:52:38 +0000","user_id":26029726,"duration":206177,"commentable":true,"state":"finished","original_content_size":3298521,"last_modified":"2014/10/01 18:56:25 +0000","sharing":"public","tag_list":"","permalink":"tere-bin-uzair-jaswal-official","streamable":true,"embeddable_by":"all","downloadable":false,"purchase_url":null,"label_id":null,"purchase_title":null,"genre":"Musical","title":"Tere Bin - Uzair Jaswal [Official Music Audio]","description":"","label_name":"","release":"","track_type":"original","key_signature":"","isrc":"","video_url":null,"bpm":null,"release_year":null,"release_month":null,"release_day":null,"original_format":"mp3","license":"all-rights-reserved","uri":"https://api.soundcloud.com/tracks/63225776","user":{"id":26029726,"kind":"user","permalink":"uzair-jaswal-1","username":"Uzair Jaswal Music","last_modified":"2014/10/19 13:06:28 +0000","uri":"https://api.soundcloud.com/users/26029726","permalink_url":"http://soundcloud.com/uzair-jaswal-1","avatar_url":"https://i1.sndcdn.com/avatars-000110064166-2ts508-large.jpg"},"permalink_url":"http://soundcloud.com/uzair-jaswal-1/tere-bin-uzair-jaswal-official","artwork_url":"https://i1.sndcdn.com/artworks-000032079002-kup6vc-large.jpg","waveform_url":"https://w1.sndcdn.com/9bwAsZfGrxwN_m.png","stream_url":"https://api.soundcloud.com/tracks/63225776/stream","playback_count":359588,"download_count":100,"favoritings_count":7557,"comment_count":491,"attachments_uri":"https://api.soundcloud.com/tracks/63225776/attachments","policy":"ALLOW"}]
this is for only one audio and that audio is not downloadable but it has download count of 100. how is this possible ?
can anybody tell me how i can download that audio which is not downloadable?
any help would be much appreciated. Thanks :)
I fix it myself, i was using android and the stream url is also a download url. the stream url is also download url for downloading but it won't affect on download count. you can try like that
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
pass this url to asyntack and manage you download there, you can pass it like that
new DownloadFileFromURL().execute(file_url);
here is DownloadFileFromUR class using asyntask
class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
URL u = null;
InputStream is = null;
try {
u = new URL(f_url[0]);
is = u.openStream();
HttpURLConnection huc = (HttpURLConnection)u.openConnection();//to know the size of video
int size = huc.getContentLength();
if(huc != null){
String fileName = "FILE2.mp3";
String storagePath = Environment.getExternalStorageDirectory().toString();
File f = new File(storagePath,fileName);
FileOutputStream fos = new FileOutputStream(f);
byte[] buffer = new byte[1024];
long total = 0;
int len1 = 0;
if(is != null){
while ((len1 = is.read(buffer)) > 0) {
total+=len1;
publishProgress((int)((total*100)/size));
fos.write(buffer,0, len1);
}
}
if(fos != null){
fos.close();
}
}
}catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(is != null){
is.close();
}
}catch (IOException ioe) {
// just going to ignore this one
}
}
return "";
}
#Override
protected void onPostExecute(String file_url) {
}
}
String file_url = "https://api.soundcloud.com/tracks/93216523/stream?client_id=4346c8125f4f5c40ad666bacd8e96498";
DownLoad Class:
private class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count;
try {
URL url = new URL(file_url);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(getOutputMediaFile());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}

Download docx file from url android

i want to download file from url. http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx - you can try it, it work. My code is next:
new DownloadFileFromURL().execute("http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx");
DownloadFileFromUrl is
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
/**
* Before starting background thread Show Progress Bar Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PostInfoActivity.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Downloading file in background thread
*/
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/test.docx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
*/
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
if (pDialog != null) {
pDialog.dismiss();
}
}
}
After this a saw new test.docx file in my root folder, but its size is 26 byte and i can not open it.
This happening because your url is in unicoded form so you have to first encode it then try to download
URLEncoder.encode(Url, "UTF-8")
It works for me.
You can try with this method by calling this method from your doInBackground
private void downloader(String urlstr) {
HttpURLConnection c = null;
FileInputStream fis = null;
FileOutputStream fbo = null;
File file = null, file1;
File outputFile = null;
InputStream is = null;
URL url = null;
try {
outputFile = new File(Environment
.getExternalStorageDirectory().toString()
+ "/test.docx");
if(outputFile.exists())
Log.e("File delete",outputFile.delete()+"");
fbo = new FileOutputStream(outputFile, false);
// connect with server where remote file is stored to download it
url = new URL(urlstr);
c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.setConnectTimeout(0);
c.connect();
is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fbo.write(buffer, 0, len1);
Log.e("length", len1+"----");
}
fbo.flush();
} catch (Exception e) {
} finally {
if (c != null)
c.disconnect();
if (fbo != null)
try {
fbo.close();
} catch (IOException e) {
e.printStackTrace();
}
if (is != null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
file = null;
outputFile = null;
}
}
I think Problem is you used only URLConnection class instead of HttpUrlConnection class. refer below link
Download a file with Android, and showing the progress in a ProgressDialog
Hey I have checked your link which you got after encoding...The Problem here is the + character which replaced the white space http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист+PHP_2013-09-03.docx.....TO resolve this issue replace your + character with %20 and then try....This will definitely work... and you can also do that before encoding i.e replace your white space with %20...so the final link should be like http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист%20PHP_2013-09-03.docx

Saving to internal storage using existing code - Android

I would rather my application save the required text file in the internal storage for the app than the users /sdcard/ so there isn't files being created which may annoy them at some point. Could someone direct me on how to change my code so the text file is saved internally rather than externally.
public void updatebutton(View v){
startDownload();
}
private void startDownload() {
String url = "http://nowactivity.webs.com/teststring.txt";
Toast.makeText(this, "Updating", Toast.LENGTH_LONG);
new DownloadFile().execute(url);
}
class DownloadFile extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/textfile.txt");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
I think what you want is Context.openFileOutput(). (Activity extends Context, so you could call this from within an Activity, for instance.)
Incidentally, you should use Environment.getExternalStorageDirectory() instead of something like "/sdcard"

Progress bar for file transfer to sd

i use the following code for downloading a file from the internet. using this code i have a progress dialog
private void startDownload() {
String url = tv.getText().toString();
new DownloadFileAsync().execute(url);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
"data/data/com.xxxxxxxx.android/app_p_pic/"
+ "blabla"
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
}
is there a way of using the above code to transfer a file from say internal to sd? at the momment i use the following code but iv been unable to get the progress to work with progress bar
protected void ontrans() {
String title = tv.getText().toString();
try {
myInput = new FileInputStream(title);
File directory = new File(Environment.getExternalStorageDirectory()
+ "/android_files/data/secure");
if (!directory.exists()) {
directory.mkdirs();
}
OutputStream myOutput = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/android_files/data/secure/" + chosenFile);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(File_exActivity.this, "file move Succesfully!",
Toast.LENGTH_SHORT).show();
showDialog(11);
} catch (FileNotFoundException e) {
Toast.makeText(File_exActivity.this, "no file found!",
Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(File_exActivity.this, "move unsuccesfull!",
Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Things to think about: you can get the size of the source file File.length() and destination. Comparing them to display the difference in the progress bar.
The File.length() method returns the following according to the javadoc:
The length, in bytes, of the file denoted by this abstract pathname,
or 0L if the file does not exist. Some operating systems may return 0L
for pathnames denoting system-dependent entities such as devices or
pipes.
What you'll need to do is to create a progress bar object (you can add it into your layout if you want or create it programmatically) then update its state inside your download while loop. The means of creating a progress bar can be found here: http://developer.android.com/reference/android/widget/ProgressBar.html

Categories

Resources