i am using below code to downloading file from URL.
URL url = new URL(mCoreContent.VideoURI);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
lenghtOfFile = c.getContentLength();
InputStream input = c.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input);
ByteArrayOutputStream output = new ByteArrayOutputStream((int) lenghtOfFile);
int buffer = 4096;
byte data[] = new byte[buffer];
int current = 0;
while ((current = bis.read(data, 0, buffer)) != -1) {
output.write(data, 0, current);
}
i tested above code with two different device. one device taking less than a minute downloading the file and another takes more than 5-10 to downloading same with same network connecting. i tested multiple times and i am getting the same result. Please help.
Thanks in advance.
Related
I am downloading HTML file from server using URLConnection but I am getting FileNotFoundException. My path is correct. Using same code same file is downloaded on android of API level 25 but on API level less than it is not downloading. Also connection.getContentLength(); is giving 311 value always. I am not getting any answer to solve this. I am hereby adding my code.
My class file code is
String HomeScreenResourcefilename = WebHomescreenResObj.getString("FileName");
int ProductTargetID = WebHomescreenResObj.getInt("ProductTargetID");
String WebURL_Part1 = context.getResources().getString(R.string.FileDownloadRootPath)+"/ExhibitorData/";
String WebURL_Part2 = GlobalVariables.tradeShowName+" - "+GlobalVariables.exhibitorName+"/HTMLHomeScreen/"+ProductTargetID +"/"+HomeScreenResourcefilename;
String WebURL = WebURL_Part1 + WebURL_Part2;
try {
URL url = new URL(WebURL);
File file = new File(context.getFilesDir(), HomeScreenResourcefilename);
URLConnection connection = url.openConnection();
connection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e1) {
e1.printStackTrace();
LogE("error in 14 :"+e1);
}
Use HttpURLConnection and then connection.getResponseCode() to get the status code. If it is greater than 400, that might be the reason.
Update: Use url encoding.
I am trying to create an app that can download music files.
How to download mp3 file in android from a URL and save it in SD card??
I use this code but lenghtOfFile always <=350:
String fileUrl = (String) params[0];
path = (String) params[1];
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
int count;
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
connection .connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = connection .getContentLength();
// downlod the file
input = new BufferedInputStream(url.openStream());
output = new FileOutputStream(path);
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();
url files :
http://snd1.tebyan.net/1391/12/08_Khaneh_D_117323.mp3
http://snd1.tebyan.net/1393/12/100_Pedar_Va_Madar_D_148797.mp3
and .....
update :
int code= connection.getResponseCode();\\302
String _result= connection.getResponseMessage();\\ found
note :
Files do download in Samsung Galaxy S3, but files do not download in Samsung tablet N8000
You could implement HMTL5 and do it from there, might need some JS...
for 302 response ,you need connection.setInstanceFollowRedirects(true) to follow it. before connection.connect()
I have a published Android application that has an HTTP audio download process.
This processed worked fine until today.
whats wrong with my code?
final URL downloadFileUrl = new URL(mPerformanceSong.getPreviewUrl());
final HttpURLConnection httpURLConnection = (HttpURLConnection) downloadFileUrl.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.connect();
mTrackDownloadFile = new File(RecordPerformance.this.getCacheDir(), "mediafile");
mTrackDownloadFile.createNewFile();
final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile);
final byte buffer[] = new byte[16 * 1024];
final InputStream inputStream = httpURLConnection.getInputStream();
int len1 = 0;
while ((len1 = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.flush();
fileOutputStream.close();
The content of the downloaded file appears to be gzip.
does this mean i need to wrap my inputStream in GZIPInputStream?
an example download URL is
http://www.amazon.com/gp/dmusic/get_sample_url.html?ASIN=B008TMSNMI
I'm actually surprised it's downloading anything - are you sure it is?
The http url that you've posted:
http://www.amazon.com/gp/dmusic/get_sample_url.html?ASIN=B008TMSNMI
Is currently redirecting to an https cloudfront address:
https://d28julafmv4ekl.cloudfront.net/...
HttpUrlConnection will not follow redirects across schemes (ie from http to https).
So if you change your *.amazon.com URLs to https, perhaps it would fix your issue...
URL url = new URL(path);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = "/mnt/sdcard/Android/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "version.txt");
if(outputFile.exists()){
outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
Exception caught: java.io.FileNotFoundException http://192.168.2.143/version.txt, where path="http://192.168.2.143/version.txt", I use browser in my device to open http://192.168.2.143/version.txt, can be opened. I have INTERNET permission in my manifest. Any idea?
It's the same problem I was having:
HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection.
You should instead use getErrorStream() when the status code is higher than 400.
More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.
Here is an example of how I went to manage it
... connection code code code ...
// Get the response code
int statusCode = connection.getResponseCode();
InputStream is = null;
if (statusCode >= 200 && statusCode < 400) {
// Create an InputStream in order to extract the response object
is = connection.getInputStream();
}
else {
is = connection.getErrorStream();
}
... callback/response to your handler....
In this way, you'll be able to get the needed response in both success and error cases.
Hope this helps!
Try this to read file over the internet: Reading Text File From Server on Android
I'm not sure you can use File.
I have an app to download zip file content from drop box (which is publicly shared path). i wrote download code using HttpURLConnection but its not working as intended and instead is downloading a small portion (after download zip file showing 31 kb but its original size is 3mb). i am attching my code. please help me to solve this.
URL url = new URL("drop box public share url");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setAllowUserInteraction(false);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setConnectTimeout(5 * 1000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"/download/sample.zip");
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
onProgressUpdate(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
inputStream.close();
It seems that the method call:
setDoOuput(true);
makes the request a POST (see
What exactly does URLConnection.setDoOutput() affect?)
Removing it seems to fix the issue.
Try to use plain URLConnection not HttpURLConnection. And see the output.