Is that possible to get data content length when WebView loading URL - android

It's very convenient to display web site with WebView in Android.
But i cannot find any method to get the whole url (including images,css) content
length.is it possible to realized ?

String url1 = "";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
URL url = new URL(revisedUrl);
URLConnection connection = url.openConnection();
connection.connect();
String result = IOUtils.toString(connection.getInputStream());
int lengthofdownfile=result.length();//content length also same like this
System.out.println(result);
System.out.print("filelength"+lengthofdownfile);
File sDownlodafile = new File(mTranscription.getfilename().getAbsoluteFile(), + dateFormat.format(date) + ".wav");
InputStream input = new BufferedInputStream(
url.openStream());
OutputStream output = new FileOutputStream(
sDownlodafile.getAbsoluteFile());
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+ (int) ((total * 100) /lengthofdownfile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();

Related

Download MP3 file from server in sd card in Android

I want to download all mp3 files from server one by one and save into sd card folder. I have no any errors or exception but mp3 does not downloaded and does not show in SD card. Can someone help how to solve this issue.Here is my code.
if (imageName.endsWith(mp3_Pattern))
{
str_DownLoadUrl = namespace + "/DownloadFile/FileName/" + imageName;
Log.e("######### ", "str_DownLoadUrl = " + str_DownLoadUrl);
download_Mp3File(str_DownLoadUrl);
strDownLoadStatus = "1";
dbhelper.update_DownLoadStatus(imageName, strDownLoadStatus);
}
void download_Mp3File(final String fileUrl) {
new AsyncTask<String, Integer, String>()
{
#Override
protected String doInBackground(String... arg0)
{
int count;
File file = new File(newFolder, System.currentTimeMillis() + imageName);
try
{
URL url = new URL(fileUrl);
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();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
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;
}
}.execute();
}
place a breakpoint in inputstream object to see is there any stream. then debug output stream to see the results.

download errors, can't open files

My app has to connect to google drive. The connection works fine.
I can see all the files in the drive. The download of the files works fine.
Unfortunately when I try to open it the files are corrupted or I can't open them at all. Does anyone know a solution for this problem ??
enter code here
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
fileName = mr.getTitle();
// opens input stream from the HTTP connection
// URLConnection connection = url.openConnection();
String saveFilePath = saveDir + File.separator + fileName;
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new
FileOutputStream(saveFilePath);
// opens an output stream to save into file
int bytesRead = 0;
// int read;
byte[] buffer = new byte[16384];
// while ((bytesRead = inputStream.read(buffer)) > 0) {
// outputStream.write(buffer, 0, bytesRead);
// }
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out
.println("No file to download. Server replied HTTP code: "
+ responseCode);
}
httpConn.disconnect();
It's problem between your file length and byte buffer. For quickly, please change to and retry
byte[] buffer = new byte[1024];
or you could get the length of input stream then create buffer
long streamLength = inputStream.available();
byte[] buffer = new byte[streamLength];
Have fun!

Android phone crashes on downloading video(mp4) file

I want my app to download a video from an url.
For now I want to write download the file to my sd card.
I tried some different scripts, I don't receive an android.os.NetworkOnMainThreadException exception. But my application crashes.
Download a file programatically on Android
What is best way to download files from net programatically in android?
Does anyone know how to create a working method?
To solve this exception it has to be an async task.
public static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(Exception e) {
Log.e("theple", "" + e);
}
}
Logs:
03-14 12:09:46.535: E/theple(6987): android.os.NetworkOnMainThreadException
I made it working, thx for the help anyway.
My code:
public class FileDownloader extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params)
{
try {
URL u = new URL(params[0]);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(new File(params[1])));
fos.write(buffer);
fos.flush();
fos.close();
} catch(Exception e) {
Log.e("theple", "" + e);
}
return null;
}
}
There are many ways you can perform downloading,in-spite of creating a method for it you should use "thread,Async class or service",That error "Network on Main thread comes due to the process is taking time".
I am showing example of Using Async Task and with Service
*
*class DownloadFile extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}**
And With Service
you can use :
class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
}
#Override
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
try {
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}
}
Hope this will be helpful for you.

Android: Complete file not downloaded from url

In my app, I have requirement to download mp3 files from url. I am downloading file using Async Task. For testing purpose, I have kept file in dropbox. The problem is, it is not downloading complete file. The actual file size is of 5 MB. But, it is downloading only 29 KB of data. When I checked the length of content, it showed -1. I am not getting where is the problem. Below, I am posting my code.
#Override
protected Void doInBackground(String... sUrl)
{
InputStream input = null;
OutputStream output = null;
try
{
URL link = new URL(sUrl[0]);
HttpURLConnection urlConnection = (HttpURLConnection)link.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
int fileLength = urlConnection.getContentLength();
Log.v("Download file length", ""+fileLength);
input = urlConnection.getInputStream();
int downloadedSize = 0;
output = new FileOutputStream(Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/audiofolder/1.mp3.mp3");
byte[] data = new byte[1024];
int bufferLength = 0;
while (((bufferLength = input.read(data)) > 0))
{
output.write(data, 0, bufferLength);
downloadedSize += bufferLength;
publishProgress((int)((downloadedSize/fileLength) * 100));
}//while
output.flush();
output.close();
input.close();
}//try
catch (MalformedURLException e)
{
e.printStackTrace();
}//catch
catch (IOException e)
{
e.printStackTrace();
}//catch
return null;
}//diInBackground
in My Application the Below Code Works Perfectly. you can try this Out.
#Override
protected Void doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
File file = new File("mnt/sdcard/");
file.mkdirs();
File outputfile = new File(file, title + ".mp3");
FileOutputStream fileOutput = new FileOutputStream(outputfile);
InputStream inputStream = conexion.getInputStream();
int totalSize = conexion.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) != -1) {
downloadedSize += bufferLength;
onProgressUpdate((int) ((downloadedSize * 100) / totalSize));
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e) {
download = true;
e.printStackTrace();
}
return null;
}
Check your link.
When you see length of content = -1, it mean there is no length of content in header of link. It don't force under your download progress.
You only download 29KB because it download website, .html not file mp3.
Yout can copy and paste your link on brower to check.
From Android Documentation:
https://developer.android.com/reference/java/net/URLConnection.html#getContentLength()
getContentLength returns:
the content length of the resource that this connection's URL references, -1 if the content length is not known, or if the content length is greater than Integer.MAX_VALUE.

How to download full data to a byte array

I want to download a zip file via a url. And I want to encrypt that without writing to the sd card. How to get full byte data from the url?
Thanks in advance
protected String doInBackground(String... url) {
int count;
try {
URL url1 = new URL(url[0]);
URLConnection conexion = url1.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(url1.openStream());
OutputStream output = new FileOutputStream(
"/sdcard/downloaded.zip");
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;
}
Use a ByteArrayOutputStream() and after downloading call toByteArray() function.

Categories

Resources